我正在尝试在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;
?>
答案 0 :(得分:1)
您应该查看相应的mysqli_stmt::bind_param文档。更准确地说,看一下函数的定义:
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
注意mixed &$var1
部分?这基本上表明你的参数是通过引用传递的,而不是通过值传递的(看起来像mixed $var1
- &
会产生差异)。
现在,调用的问题在于您尝试通过引用传递表达式而不是变量。来自PHP documentation:
以下内容可参考:
返回的引用
- 变量,即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;
}