尝试预准备语句时无法传递参数


Cannot pass parameter when attempting prepared statement

我现在正在尝试在 PHP/MYSQL 中学习准备好的语句,因为这里有许多建议。我不断收到此错误:

Fatal error: Cannot pass parameter 2 by reference in C:'xampp'htdocs'blog'admin'create.php on line 57

谁能告诉我如何解决这个问题?我一直在四处寻找,找不到任何可以帮助我解决这个问题的东西。

这是我的代码:

<?php
require_once '../config.php';
// Check to see if the title was entered from new.php
if ($_POST['title'])
{
$title = $_POST['title'];
} else {
echo "No title was entered. Please go back. <br />";
}
// Check to see if the body was entered from new.php
if ($_POST['body'])
{
$body = $_POST['body'];
} else {
echo "No body was entered. Please go back. <br />";
}
// Get the date
$date = time();
// ID = NULL because of auto-increment
$id = 'NULL';
// If magic_quotes_gpc returns true then it's enabled on the serever and all variables   will be
// automatically escaped with slashes. If it isn't true then it's done manually
if (!get_magic_quotes_gpc())
{
$title = addslashes($title);
$body = addslashes($body);
$date = addslashes($date);
}
// Connect to the database
$db = new mysqli('localhost','username','password','database');
// Check to see if the connection works
if ($db->connect_errno)
{
echo 'Error: Could not connect to database. Please try again.';
exit;
}
// Prepared statement for a query to place something in the database
if(!($stmt = $db->prepare("insert into pages (id, title, body, date) values (?,?,?,?)")))
{
echo "Prepare failed: (" .$db->errno . ")" . $db->error;
}
// THIS IS THE LINE WHERE I'M RECEIVING THE ERROR!!!!!!!!
if (!$stmt->bind_param('isss', ''.$id.'', ''.$title.'',''.$body.'',''.$date.''))
{
echo "Binding parameters failed: (" .$stmt->errno. ")" . $stmt->error;
}
if (!$stmt->execute())
{
echo "Execute failed: (" .$stmt->errno . ") " .$stmt->error;
}
$db->close;
?>

您应该查看相应的 mysqli_stmt::bind_param 文档。更准确地说,看看函数的定义:

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

注意到mixed &$var1部分了吗?这基本上表明您的参数是通过引用而不是按值传递的(看起来像mixed $var1 - &会有所不同)。

现在,调用的问题在于您尝试通过引用传递表达式而不是变量。从 PHP 文档中:

可以通过引用传递以下内容:
- 变量,即 foo($a)
- 新语句,即 foo(new foobar())
- 从函数返回的引用,[...]

简单的补救措施是首先使用未初始化的变量调用绑定,然后为处理后的输入数据分配这些变量,即

// Prepared statement for a query to place something in the database
$stmt = $db->prepare("insert into pages (id, title, body, date) values (?,?,?,?)");
if ( !$stmt ) {
    echo "Prepare failed: (" .$db->errno . ")" . $db->error;
}
if ( !$stmt->bind_param('isss', $stmt_id, $stmt_title, $stmt_body, $stmt_date) ) {
    echo "Binding parameters failed: (" .$stmt->errno. ")" . $stmt->error;
}
$stmt_id    = (int) $id;
$stmt_title = (string) $title;
$stmt_body  = (string) $body;
$stmt_date  = (string) $date;
if ( !$stmt->execute() ) {
    echo "Execute failed: (" .$stmt->errno . ") " .$stmt->error;
}