当我编写此代码时,我收到致命错误:
调用非对象中的成员函数query() 第27行的C:\ wamp \ www \ demo.php。
如何摆脱这个错误?
<!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>
答案 0 :(得分:1)
if ($mysqli = false)
此行将布尔值false
指定给$mysqli
。将其更改为:
if ($mysqli == false)
或(更好)if ($mysqli === false)
。
为防止以后出现此错误,建议您使用Yoda conventions。换句话说:
if (false === $mysqli)
答案 1 :(得分:0)
是:
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
根据http://www.php.net/manual/en/mysqli.query.php
此外,查询执行需要更改为
if($mysqli->query($sql)) {
答案 2 :(得分:0)
在您的代码中检查
if($mysqli = false)
当你想要的是什么
if($mysqli == false)
但是,如果存在连接问题,这将无效,因为您仍会获得mysqli实例。你正在寻找
if($mysqli->connect_error)
有关详细信息,请参阅here