PHP查询数据库数据时出现错误

clearskyo 2012-03-08 04:45:42
PHP 查询数据库books中的books表时出现以下错误!

Notice: Trying to get property of non-object in D:\wamp\Apache\htdocs\php\results.php on line 33

Fatal error: Call to a member function fetch_assoc() on a non-object in D:\wamp\Apache\htdocs\php\results.php on line 35


代码如下:


<html>
<head>
<title> Book-O-Rama Catalog Search</title>
</head>
<body>
<h1>Book-O-Rama Catalog Search</h1>
<?php
//create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);

if (!$searchtype || !$searchterm) {
exit('You have not entered search detais,please go back again');
}

if (!get_magic_quotes_gpc()){

$searchtype=addslashes($searchtype);
$searchterm=addslashes($searchterm);
}


@ $db=new mysqli('localhost','root','password','books');

if (mysqli_connect_errno()){
echo "could not connect to database,please try again later.".mysqli_connect_errno();
exit;
}else {
$sql ="select * from books where".$searchtype."like'%".$searchterm."%'";

$result=$db->query($sql);
$num_result=$result->num_rows;
for ($i=0;$i<=$num_result;$i++){
$row=$result->fetch_assoc();
echo "<p>".($i+1)."title:";
echo htmlspecialchars(stripslashes($row['author']));
echo "Author:".stripslashes($row->newsauthor);
echo "ISBN:".stripslashes($row->newsISBN);
echo "price:".stripslashes($row->newsprice)."</p>";
}
}

$result->free();
$db->colse();
?>
</body>
</html>


上述问题那微微大虾能给个解决方案!
...全文
45 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
coder 2012-03-08
  • 打赏
  • 举报
回复

$sql ="select * from books where ".$searchtype." like '%".$searchterm."%'";

if ($result=$db->query($sql)) {
$num_result=$result->num_rows;
for ($i=0;$i<=$num_result;$i++){
$row=$result->fetch_assoc();
echo "<p>".($i+1)."title:";
echo htmlspecialchars(stripslashes($row['author']));
echo "Author:".stripslashes($row->newsauthor);
echo "ISBN:".stripslashes($row->newsISBN);
echo "price:".stripslashes($row->newsprice)."</p>";
}
}else{
echo "fail.";
exit;
}



$sql =" select * from books where ".$searchtype." like '%".$searchterm."%'";

字符串连在一块了。所以,语句不对。
if ($result=$db->query($sql)) {最好这样。
因为$db->query($sql)会返回一个false,导致没有num_rows这个属性。
bill19832004 2012-03-08
  • 打赏
  • 举报
回复
感觉你没有连接数据库吧!!!

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧