Stored Procedures

The MySQL database supports stored procedures. A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The CALL SQL statement is used to execute a stored procedure.

Parameter

Stored procedures can have IN, INOUT and OUT parameters, depending on the MySQL version. The mysqli interface has no special notion for the different kinds of parameters.

IN parameter

Input parameters are provided with the CALL statement. Please, make sure values are escaped correctly.

Example #1 Calling a stored procedure

<?php
$mysqli 
= new mysqli("example.com""user""password""database");
if (
$mysqli->connect_errno) {
    echo 
"Failed to connect to MySQL: (" $mysqli->connect_errno ") " $mysqli->connect_error;
}

if (!
$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo 
"Table creation failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!
$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !
$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;")) {
    echo 
"Stored procedure creation failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!
$mysqli->query("CALL p(1)")) {
    echo 
"CALL failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!(
$res $mysqli->query("SELECT id FROM test"))) {
    echo 
"SELECT failed: (" $mysqli->errno ") " $mysqli->error;
}

var_dump($res->fetch_assoc());
?>

以上例程会输出:

array(1) {
  ["id"]=>
  string(1) "1"
}

INOUT/OUT parameter

The values of INOUT/OUT parameters are accessed using session variables.

Example #2 Using session variables

<?php
$mysqli 
= new mysqli("example.com""user""password""database");
if (
$mysqli->connect_errno) {
    echo 
"Failed to connect to MySQL: (" $mysqli->connect_errno ") " $mysqli->connect_error;
}

if (!
$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !
$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;')) {
    echo 
"Stored procedure creation failed: (" $mysqli->errno ") " $mysqli->error;
}


if (!
$mysqli->query("SET @msg = ''") || !$mysqli->query("CALL p(@msg)")) {
    echo 
"CALL failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!(
$res $mysqli->query("SELECT @msg as _p_out"))) {
    echo 
"Fetch failed: (" $mysqli->errno ") " $mysqli->error;
}

$row $res->fetch_assoc();
echo 
$row['_p_out'];
?>

以上例程会输出:

Hi!

Application and framework developers may be able to provide a more convenient API using a mix of session variables and databased catalog inspection. However, please note the possible performance impact of a custom solution based on catalog inspection.

Handling result sets

Stored procedures can return result sets. Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query(). The mysqli_query() function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli_query() to fail returning the user expected result sets.

Result sets returned from a stored procedure are fetched using mysqli_real_query() or mysqli_multi_query(). Both functions allow fetching any number of result sets returned by a statement, such as CALL. Failing to fetch all result sets returned by a stored procedure causes an error.

Example #3 Fetching results from stored procedures

<?php
$mysqli 
= new mysqli("example.com""user""password""database");
if (
$mysqli->connect_errno) {
    echo 
"Failed to connect to MySQL: (" $mysqli->connect_errno ") " $mysqli->connect_error;
}

if (!
$mysqli->query("DROP TABLE IF EXISTS test") ||
    !
$mysqli->query("CREATE TABLE test(id INT)") ||
    !
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo 
"Table creation failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!
$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;')) {
    echo 
"Stored procedure creation failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!
$mysqli->multi_query("CALL p()")) {
    echo 
"CALL failed: (" $mysqli->errno ") " $mysqli->error;
}

do {
    if (
$res $mysqli->store_result()) {
        
printf("---\n");
        
var_dump($res->fetch_all());
        
$res->free();
    } else {
        if (
$mysqli->errno) {
            echo 
"Store failed: (" $mysqli->errno ") " $mysqli->error;
        }
    }
} while (
$mysqli->more_results() && $mysqli->next_result());
?>

以上例程会输出:

---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
}
---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

Use of prepared statements

No special handling is required when using the prepared statement interface for fetching results from the same stored procedure as above. The prepared statement and non-prepared statement interfaces are similar. Please note, that not every MYSQL server version may support preparing the CALL SQL statement.

Example #4 Stored Procedures and Prepared Statements

<?php
$mysqli 
= new mysqli("example.com""user""password""database");
if (
$mysqli->connect_errno) {
    echo 
"Failed to connect to MySQL: (" $mysqli->connect_errno ") " $mysqli->connect_error;
}

if (!
$mysqli->query("DROP TABLE IF EXISTS test") ||
    !
$mysqli->query("CREATE TABLE test(id INT)") ||
    !
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo 
"Table creation failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!
$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;')) {
    echo 
"Stored procedure creation failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!(
$stmt $mysqli->prepare("CALL p()"))) {
    echo 
"Prepare failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!
$stmt->execute()) {
    echo 
"Execute failed: (" $stmt->errno ") " $stmt->error;
}

do {
    if (
$res $stmt->get_result()) {
        
printf("---\n");
        
var_dump(mysqli_fetch_all($res));
        
mysqli_free_result($res);
    } else {
        if (
$stmt->errno) {
            echo 
"Store failed: (" $stmt->errno ") " $stmt->error;
        }
    }
} while (
$stmt->more_results() && $stmt->next_result());
?>

Of course, use of the bind API for fetching is supported as well.

Example #5 Stored Procedures and Prepared Statements using bind API

<?php
if (!($stmt $mysqli->prepare("CALL p()"))) {
    echo 
"Prepare failed: (" $mysqli->errno ") " $mysqli->error;
}

if (!
$stmt->execute()) {
    echo 
"Execute failed: (" $stmt->errno ") " $stmt->error;
}

do {

    
$id_out NULL;
    if (!
$stmt->bind_result($id_out)) {
        echo 
"Bind failed: (" $stmt->errno ") " $stmt->error;
    }
 
    while (
$stmt->fetch()) {
        echo 
"id = $id_out\n";
    }
} while (
$stmt->more_results() && $stmt->next_result());
?>

See also

User Contributed Notes

Valverde 05-Jul-2019 08:16
<?php

// Store procedure call without params

$MyConnection = new mysqli ("DB_SERVER", "DB_USER", "DB_PASS", "DB_NAME");

mysqli_multi_query ($MyConnection, "CALL MyStoreProcedure") OR DIE (mysqli_error($MyConnection));

while (
mysqli_more_results($MyConnection)) {

       if (
$result = mysqli_store_result($MyConnection)) {

              while (
$row = mysqli_fetch_assoc($result)) {

                    
// i.e.: DBTableFieldName="userID"
                    
echo "row = ".$row["DBTableFieldName"]."<br />";
                     ....

              }
             
mysqli_free_result($result);
       }
      
mysqli_next_result($conn);

}
?>
*******************************************************************
<?php

// Store procedure call using params

$MyConnection = new mysqli ("DB_SERVER", "DB_USER", "DB_PASS", "DB_NAME");

mysqli_query($MyConnection ,"SET @p0='".$MyParam1."'");
mysqli_query($MyConnection ,"SET @p1='".$MyParam2."'");
mysqli_multi_query ($MyConnection, "CALL MyStoreProcedure (@p0,@p1)") OR DIE (mysqli_error($MyConnection));

while (
mysqli_more_results($MyConnection)) {

       if (
$result = mysqli_store_result($MyConnection)) {

              while (
$row = mysqli_fetch_assoc($result)) {

                    
// i.e.: DBTableFieldName="userID"
                    
echo "row = ".$row["DBTableFieldName"]."<br />";
                     ....

              }
             
mysqli_free_result($result);
       }
      
mysqli_next_result($conn);

}
?>
paulo dot reis dot rosa at gmail dot com 27-Nov-2016 09:39
<?php
   
/**
    * Small function to facilitate call procedure with multiple arguments (supports in/inout/out)
    */
   
$db = new mysqli('localhost', 'root', 'password', 'database');

   
$lt_query = callProcedure(
       
$db,
       
"stored_procedure",
        array(
           
"in_param1"    => "Value1",
           
"in_param2"    => "Value2",
           
"inout_param3" => "Value3",
           
"out_param4"   => "",
           
"out_param5"   => ""
       
));

    function
callProcedure( $po_db, $pv_proc, $pt_args )
    {
        if (empty(
$pv_proc) || empty($pt_args))
        {
            return
false;
        }
       
$lv_call   = "CALL `$pv_proc`(";
       
$lv_select = "SELECT";
       
$lv_log = "";
        foreach(
$pt_args as $lv_key=>$lv_value)
        {
           
$lv_query = "SET @_$lv_key = '$lv_value'";
           
$lv_log .= $lv_query.";\n";
            if (!
$lv_result = $po_db->query($lv_query))
            {
               
/* Write log */
               
return false;
            }
           
$lv_call   .= " @_$lv_key,";
           
$lv_select .= " @_$lv_key AS $lv_key,";
        }
       
$lv_call   = substr($lv_call, 0, -1).")";
       
$lv_select = substr($lv_select, 0, -1);
       
$lv_log .= $lv_call;
        if (
$lv_result = $po_db->query($lv_call))
        {
            if(
$lo_result = $po_db->query($lv_select))
            {
               
$lt_result = $lo_result->fetch_assoc();
               
$lo_result->free();
                return
$lt_result;
            }
           
/* Write log */
           
return false;
        }
       
/* Write log */
       
return false;
    }
   
   
/**
    * This will return an array like this:
    *
    * $lt_query = array(
    *     'in_param1'   = 'Value1', // Same value as in call
    *     'in_param2'   = 'Value2', // Same value as in call
    *     'inout_param3' = ?,       // Value is changed accordingly
    *     'out_param4'   = ?,       // Value is changed accordingly
    *     'out_param5'   = ?        // Value is changed accordingly
    * )
    */
?>
Jonathon 24-May-2013 05:30
<?php
/*
*
*Creating Session Variable with Prepared Statement
*
*for IN/OUT variable to stored procedure
*
*using Data Binding to get the data back
*
*@params
*    $mysql: mysqli() instance
*    $var: input and output paramater to stored procedure
*/
 
function stored_procedure($mysql , &$var = 'hello world')
    {
       
$stmt = $mysql->stmt_init(); // initialize statement
       
       
if($stmt->prepare("SET @var = ?")) // prepare set command
       
{
           
$var = $mysql->real_escape_string($var); // escape input
           
           
$stmt->bind_param('s',$var); // bind data
          
           
$stmt->execute(); // create session variable
          
           
$stmt->free_result(); // free resutl
          
           
if($stmt->prepare("CALL stored_procedure(@var)"))//call stored procedure with database server session variable
           
{
               
$stmt->execute();

               
$stmt->free_result();
            }
           
            if(
$stmt->prepare(" SELECT @var AS var ")) // prepare command to select the database server session variable
           
{
               
$stmt->execute(); // execure
               
               
$out_var = NULL;

               
$stmt->bind_result($out_var); // bind
          
               
$stmt->fetch(); // fetch one row
               
               
echo $out_var.'<br />';// display OUT variable
           
}
        }
    }
?>