When I am writing this code, I am getting a fatal error stating:
Call to a member function query() on a non-object in C:\wamp\www\demo.php on line 27.
How can I get rid of this error?
<!DOCTYPE html>
<html>
<body>
<?php
$searchtype = $_POST["searchtype"];
$searchterm = $_POST["searchterm"];
$searchterm = trim($searchterm);
if(!$searchtype && !$searchterm) {
echo "You have not entered search details.";
}
$mysqli = new mysqli("localhost","root","","books");
if($mysqli = false) {
echo "ERROR:Sorry,Could Not Connect To The Database.";
} else {
echo "Connected To Database";
}
$sql = "SELECT author FROM books";
if($mysqli -> query($sql)) {
echo "Connected To Tables";
} else {
echo "Cannot connect tot tables right now.";
}
?>
</html>
if ($mysqli = false)
This line is assigning the boolean value false
to $mysqli
. Change it to: if ($mysqli == false)
or (better yet) if ($mysqli === false)
.
To prevent this error in the future, I recommend you employ Yoda conventions. In other words:
if (false === $mysqli)
It is:
if ($mysqli->connect_errno) {
printf("Connect failed: %s
", $mysqli->connect_error);
exit();
}
as per http://www.php.net/manual/en/mysqli.query.php
Also the query execution need to change to
if($mysqli->query($sql)) {
In your code you check
if($mysqli = false)
when what you want is
if($mysqli == false)
However, this will not work if there is a connection problem as you will still get a mysqli instance back. You're looking for
if($mysqli->connect_error)
See here for more info