简体   繁体   中英

Call MySql Stored Procedure from PHP (PDO)

I am trying to execute a MySQL Stored Procedure using PDO connection, i tried almost everything but not able to execute it.

The SP will only insert and update. Following is the codes I tried till now.

$config = require('protected/config/main.php');
try
{
$db_adat = new PDO($config['components']['db']['connectionString'], $config['components']    ['db']['username'], $config['components']['db']['password']);
$result= $db_adat->prepare('CALL pdv()');

 $a = $result->execute();
 $a->fetchAll(PDO::FETCH_ASSOC);

I tried with only fetch(), with only fetchAll(), fetchObject(), with fetch(PDO::FETCH_ASSOC), with fetchAll(\\PDO::FETCH_ASSOC), but I always get following error

Fatal error: Call to a member function fetchAll() on a non-object in D:\ADAT_System\www\test\protected\controllers\ExportPDVController.php on line 35

I also tried using query() instead of execute(), but that doesn't work either.

I also tried adding a (select * ) statement in SP and tried with all above "fetch" options, but got same error.

The SP takes 7 minutes to complete, but all gave error immediately, so I am guessing it never ran the SP.

I tried as following too

$result= $this->$db_adat->prepare("CALL pdv()");
$result->execute();

but the I got following error:

Object of class PDO could not be converted to string 

I am not passing any parameters in SP, just a simple call. Please let me know if any more information is required.

This part of your code is wrong

$result= $db_adat->prepare('CALL pdv()');
$a = $result->execute();
$a->fetchAll(PDO::FETCH_ASSOC);

Because execute() returns a boolean upon success or failure.

You cannot use that to fetch.here is the proper way with appropriate variable names:

$stmt= $db_adat->prepare('CALL pdv()');
$success = $stmt->execute();
if($success){
   $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}else{
   echo 'failed to run sp';
}
<?php
  if(isset($_POST) && !empty($_POST)){
    $SearchPO = (($_POST)['SearchPO']);
    
  } 
    $stmt = $pdo->prepare("CALL spPO(?)");
    $stmt->bindParam(1, $SearchPO, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT|PDO::ATTR_EMULATE_PREPARES, 4000);
    $stmt->execute(); 
    do {
    $result = $stmt->fetchAll();                    
  } while ($stmt->nextRowset() && $stmt->columnCount());
?> 

You must use the nextRowset() function because the next record is 'empty' without it. Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM