如何使用mysqli准备好的语句? [英] How to use mysqli prepared statements?
问题描述
我正在尝试准备好的语句,但下面的代码不起作用.我收到错误:
I am trying out prepared statements, but the below code is not working. I am getting the error:
致命错误:在非对象上调用成员函数execute()/var/www/prepared.php 第 12 行
Fatal error: Call to a member function execute() on a non-object in /var/www/prepared.php on line 12
<?php
$mysqli = new mysqli("localhost", "root", "root", "test");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
$stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)");
// insert one row
$stmt->execute(array('one',1));
// insert another row with different values
$stmt->execute(array('two',1));
?>
另外,我是否需要将 mysqli 用于准备好的语句?任何人都可以向我指出一个完整的示例,从连接到插入再到带有错误处理的选择的准备语句?
Also, do I need to use mysqli for prepared statements? Can anyone point me to a complete example on prepared statements from connection to insertion to selection with error handling?
推荐答案
From the mysqli::prepare
docs:
在执行语句或获取行之前,必须使用 mysqli_stmt_bind_param() 和/或 mysqli_stmt_bind_result() 将参数标记绑定到应用程序变量.
The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.
即:
$name = 'one';
$age = 1;
$stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)");
// bind parameters. I'm guessing 'string' & 'integer', but read documentation.
$stmt->bind_param('si', $name, $age);
// *now* we can execute
$stmt->execute();
这篇关于如何使用mysqli准备好的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!