我在使用函数fetch_assoc
时我的代码出错了<?php
include_once('functions.php');
$book_selected=$_POST['book_selected'];
$database = new mysqli('127.0.0.1', 'user', 'user', 'library');
$query = 'SELECT * FROM book WHERE title=\'' . $book_selected . '\'';
$result_set = $database->query($query);
$row = $result_set->fetch_assoc();
var_dump($row);
$query = 'UPDATE poll_result SET num_poll = num_poll + 1 WHERE id='. $row['id'];
$database->query($query);
redirect('show_polling.php');
?>
我得到了错误:
致命错误:在非对象
上调用成员函数fetch_assoc()
我不知道如何解决它。
感谢您的建议
答案 0 :(得分:0)
我很确定您的查询中有错误。
试试这个:
<?php
include_once('functions.php');
$database = new mysqli('127.0.0.1', 'user', 'user', 'library');
if ($database->connect_error) {
die('Connect Error: ' . $database->connect_error);
}
$book_selected = $database->real_escape_string($_POST['book_selected']);
$query = 'SELECT * FROM book WHERE title=\'' . $book_selected . '\'';
$result_set = $database->query($query);
if (!$result_set) {
die(sprintf("Error: %s", $database->error));
}
$row = $result_set->fetch_assoc();
var_dump($row);
$query = 'UPDATE poll_result SET num_poll = num_poll + 1 WHERE id='. $row['id'];
$database->query($query);
redirect('show_polling.php');
?>
除此之外,您不应直接在查询中传递变量(SQL注入的可能性)。在上面的示例中,我使用mysqli :: real_escape_string转义了查询,但通常情况下,最好准备查询:http://php.net/manual/en/mysqli.prepare.php