2

由于这里有很多建议,我现在正在尝试在 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;

?>
4

1 回答 1

1

您应该查看相应的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;
}
于 2012-08-14T07:22:50.680 回答