gpt4 book ai didi

php - 如何使用 mysqli 预处理语句?

转载 作者:可可西里 更新时间:2023-11-01 07:02:55 24 4
gpt4 key购买 nike

我正在尝试准备好的语句,但下面的代码不起作用。我收到错误:

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?谁能给我指出一个完整的示例,说明从连接到插入再到带有错误处理的选择的准备语句?

最佳答案

来自mysqli::prepare docs :

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.

bind_param docs .

即:

$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();

关于php - 如何使用 mysqli 预处理语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9629328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com