i have an error in my code while using function 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');
?>
and I got the error :
Fatal error: Call to a member function fetch_assoc() on a non-object
I don't know how to fix it.
Thanks for advice
I'm pretty sure you have an error in your query.
Try this:
<?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');
?>
In addition to that, you should not pass a variable directly in a query (possibility of SQL injections). In the example above, I escaped the query with mysqli::real_escape_string, but in common, it's better to prepare the query: http://php.net/manual/en/mysqli.prepare.php