update page now

Voting

The Note You're Voting On

theking2(at)king.ma
2 years ago
Example #5 gives an 1414 wenn tried on MariaDB. Use this function to call a stored procedure with the last parameter as INOUT returning a value like a (uu)id or a count;

<?php
/**
 * call_sp Call the specified stored procedure with the given parameters.
 * The first parameter is the name of the stored procedure.
 * The remaining parameters are the (in) parameters to the stored procedure.
 * the last (out) parameter should be an int like state or number of affected rows.
 *
 * @param  mixed $sp_name The name of the stored procedure to call.
 * @param  mixed $params The parameters to pass to the stored procedure.
 * @return int The number of affected rows.
 */
function call_sp( \PDO $db, string $sp_name, ...$params ): mixed
{
  $placeholders   = array_fill( 0, count( $params ), "?" );
  $placeholders[] = "@new_id";

  $sql = "CALL $sp_name( " . implode( ", ", $placeholders ) . " ); SELECT @new_id AS `new_id`";

  try {
    LOG->debug( "calling Stored Procedure", [ "sql" => $sql ] );

    $stmt = $db->prepare( $sql );
    $i    = 0;
    foreach( $params as $param ) {
      $stmt->bindValue( ++$i, $param );
    }
    $stmt->execute();
    $new_id = $stmt->fetch( PDO::FETCH_ASSOC )['new_id'];

    return $new_id;

  } catch ( \Exception $e ) {
    LOG->error( "Error calling Stored Procedure", [ "sql" => $sql, "params" => $params, "error" => $e->getMessage() ] );
    throw $e;
  }

<< Back to user notes page

To Top