PHP -> PDO -> prepare -> 调用过程 -> 插入 -> 绑定参数


PHP -> PDO -> Prepare -> Call Procedure -> Insert Into -> Bind Parameters

使用此过程

CREATE PROCEDURE `Insert_New_Return_Id`(IN Insert_Stmnt varchar(1000), OUT IDNum int)
BEGIN
    SET @buffer = Insert_Stmnt;
    PREPARE stmt FROM @buffer;
    EXECUTE stmt;
    SELECT LAST_INSERT_ID() INTO IDNum;
    DEALLOCATE PREPARE stmt;
END 

以下代码工作正常:

$statement=$con->prepare("CALL Insert_New_Return_Id ('"INSERT INTO users (first_name,last_name)VALUES('test','test')'",@ID)");
$statement->execute();
$statement=$con->query("SELECT @ID");
while ($row = $statement->fetch()){echo "Last ID Insert : " . $row['@ID'];}

但是当我尝试绑定参数时,值?

$first_name = "test";
$last_name = "test";    
$statement=$con->prepare("CALL Insert_New_Return_Id ('"INSERT INTO users (first_name,last_name)VALUES('?','?')'",@ID)");
    $statement->bindParam(1, $first_name, PDO::PARAM_STR);
    $statement->bindParam(2, $last_name, PDO::PARAM_STR);
    $statement->execute();
    $statement=$con->query("SELECT @ID");
    while ($row = $statement->fetch()){echo "Last ID Insert : " . $row['@ID'];}

如果我尝试VALUES(?,?)返回错误。

我怎样才能做到这一点?使用 prepare 语句和绑定参数调用过程?

谢谢

$statement->bindParam(1, 'test', PDO::PARAM_STR);
$statement->bindParam(2, 'test', PDO::PARAM_STR);

您必须使用变量而不是字符串"test"。PDOStatement::bindParam 通过引用绑定变量。根据定义,不能使用字符串执行此操作。请改用变量。

$statement->bindParam(1, $str1, PDO::PARAM_STR);
$statement->bindParam(2, $str2, PDO::PARAM_STR);

此外,如果要使用 CALL 调用存储过程,只需按名称调用存储过程。不要重复查询。当然,这假设您已经完成了将存储过程添加到 MySQL 的工作。

$statement=$con->prepare('CALL Insert_New_Return_Id(?,?)');

如果需要第三个参数,请将其添加到 MySQL 中的存储过程中并像这样调用它。

$statement=$con->prepare('CALL Insert_New_Return_Id(?,?,?)');