PHP mysqli 中的存储过程和准备语句


Stored Procedures and Prepared Statements ins PHP mysqli

你能帮我这个吗:我正在编写PHP代码,并在MySQL中创建了一个存储过程,该过程接收两个输入值并返回一个输出参数

DELIMITER $$
USE `ejemplo`$$
DROP PROCEDURE IF EXISTS `insert_sp`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_sp`(
    IN ID VARCHAR(8),
    IN Nombre VARCHAR(50),
    OUT msg VARCHAR(50)
    )
BEGIN
    INSERT INTO empleado_php VALUES (ID, Nombre);
    SELECT "Todo bien" INTO msg;
    END$$
DELIMITER ;

并通过 mysqli 调用它,如果我使用下面截取的代码,一切都可以正常工作

if (!$mysqli->query("SET @msg = ''") ||
    !$mysqli->query("CALL insert_sp('" . $id . "', '" . $nombre . "', @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'];

我的问题是:如果我必须使用预准备语句,我应该如何编码?你能给我举个例子吗?这就是我到目前为止得到的,但不起作用

if (!$mysqli->prepare("SET @msg = ''") ||
         !$mysqli->prepare("CALL insert_sp(?,?,@msg)"))
     echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
  if (!($res = $mysqli->prepare("SELECT @msg as _p_out")))
     echo "Fetch failed: (" . $mysqli->errno . ") " . $mysqli->error;
  if(!$mysqli->bind_param("ss", $id, $nombre)){
         echo "Error en bind-param ingresar_sp.php " .$mysqli->connect_error;
     }
    $mysqli->execute();
    $row = $res->fetch_assoc();
    echo $row['_p_out'];

顺便一提。。。我需要通过回显显示输出值。

提前谢谢。

很容易,PHP官方网站评论你必须使用会话变量(MySQL会话,而不是PHP),所以,我的问题的答案如下所示:

// bind the value of the first IN parameter to the session variable @id     
$stmt = $mysqli->prepare("SET @id = ?");
$stmt->bind_param('s', $id);
$stmt->execute();
// bind the value of the second IN parameter to the session variable @nombre
$stmt = $mysqli->prepare("SET @nombre = ?");
$stmt->bind_param('s', $nombre);
$stmt->execute();
//bind the value of the OUT parameter
$stmt = $mysqli->prepare("SET @msg = ''");
$stmt->execute();
// execute the stored Procedure
$result = $mysqli->query('call insert_sp(@id, @nombre, @msg)');
// getting the value of the OUT parameter
$r = $mysqli->query('SELECT @msg as _p_out');
$row = $r->fetch_assoc();                       
echo $row['_p_out'];