PHP-> PDO->准备->呼叫程序->插入-->绑定参数 [英] PHP -> PDO -> Prepare -> Call Procedure -> Insert Into -> Bind Parameters

查看:83
本文介绍了PHP-> PDO->准备->呼叫程序->插入-->绑定参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此过程

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 

以下代码可以正常工作:

the following code works fine :

$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'];}

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

but when i'm trying to bind parameters the values are ?

$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语句和绑定参数的过程吗?

How can i make this work? Call a procedure with prepare statement and binding parameters?

谢谢

推荐答案

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

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

You must use a variable instead of the string 'test'. PDOStatement::bindParam binds variables by reference. By definition, you cannot do this with a string. Use a variable instead.

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

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

Also, when you want to use CALL to call a stored procedure, just call the stored procedure by name. Do not repeat the query. Of course, this assumes you've done the work of adding the stored procedure to MySQL.

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

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

If you need a third parameter, add it to the stored procedure in MySQL and call it like this.

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

这篇关于PHP-> PDO->准备->呼叫程序->插入-->绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆