如何在 PHP 中运行 bind_param() 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15748254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:53:06  来源:igfitidea点击:

How to run the bind_param() statement in PHP?

phpmysqliprepared-statement

提问by Lucio

I'm trying to make the following code work but I can't reach the execute()line.

我正在尝试使以下代码工作,但我无法到达该execute()行。

$mysqli = $this->ConnectLowPrivileges();
echo 'Connected<br>';
$stmt = $mysqli->prepare("SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`=?");
echo 'Prepared and binding parameters<br>';
$stmt->bind_param('i', 2 );
echo 'Ready to execute<br>'
if ($stmt->execute()){
    echo 'Executing..';
    }
} else {
    echo 'Error executing!';
}
mysqli_close($mysqli);

The output that I get is:

我得到的输出是:

Connected
Prepared and binding parameters

So the problem shouldbe at line 5, but checking the manual of bind_param()I can't find any syntax error there.

所以问题应该在第 5 行,但是检查我的手册在bind_param()那里找不到任何语法错误。

回答by MichaelRushton

When binding parameters you need to pass a variable that is used as a reference:

绑定参数时,您需要传递一个用作引用的变量:

$var = 1;

$stmt->bind_param('i', $var);

See the manual: http://php.net/manual/en/mysqli-stmt.bind-param.php

参见手册:http: //php.net/manual/en/mysqli-stmt.bind-param.php

Note that $vardoesn't actually have to be defined to bind it. The following is perfectly valid:

请注意,$var实际上不必定义来绑定它。以下是完全有效的:

$stmt->bind_param('i', $var);

foreach ($array as $element)
{

    $var = $element['foo'];

    $stmt->execute();

}

回答by x00

here it is just a simple explaination
declare a variable to be bind

这里只是一个简单的解释,
声明一个要绑定的变量

    $var="email";
$mysqli = $this->ConnectLowPrivileges();
echo 'Connected<br>';

$var="email";
$stmt = $mysqli->prepare("SELECT name, lastname FROM tablename WHERE idStudent=?" LIMIT=1);
echo 'Prepared and binding parameters<br>';
$stmt->bindparam(1,$var); 

回答by Your Common Sense

Your actual problem is not at line 5 but rather at line 1.
You are trying to use unusable driver.
While PDOdoes exactly what you want.

您的实际问题不在第 5 行,而是在第 1 行。
您正在尝试使用无法使用的驱动程序。
PDO正是您想要的。

$sql = "SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`=?"
$stm = $this->pdo->prepare($sql);
$stm->execute(array(2));
return $stm->fetch();


After all the years passed since this answer has been written, a new PHP feature emerged, called "argument unpacking". So, since version 5.6 you can pass a value into bind_param:

自从写下这个答案以来,已经过去了很多年,出现了一个新的 PHP 特性,称为“参数解包”。因此,从 5.6 版开始,您可以将值传递给 bind_param:

$stmt->bind_param('i', ...[2]);

But still you have a trouble with getting your data back out of a prepared statement :)

但是您仍然无法从准备好的语句中取回数据:)