数据库搜索结果给出试图在$ result上获取非对象错误的属性

时间:2014-11-07 21:06:05

标签: php mysql

当我运行搜索脚本时,我收到以下错误 尝试在第32行的C:\ xampp \ htdocs \ results.php中获取非对象的属性 为什么它告诉我它不是一个对象?它显然在第47行给出了类似的错误。 我将不胜感激任何帮助。 谢谢

7<?php
8  // create short variable names
9  $searchtype=$_POST['searchtype'];
10  $searchterm=trim($_POST['searchterm']);
11
12 if (!$searchtype || !$searchterm) {
13    echo 'You have not entered search details.  Please go back and try again.';
14     exit;
15 }
16
17  if (!get_magic_quotes_gpc()){
18    $searchtype = addslashes($searchtype);
19    $searchterm = addslashes($searchterm);
20  }
21
22  @ $db = new mysqli('localhost', 'printfactory0', '*********', 'printfactory');
23
24  if (mysqli_connect_errno()) {
25     echo 'Error: Could not connect to database.  Please try again later.';
26     exit;
27  }
28
29  $query = "select * from printfactory where ".$searchtype." like '%".$searchterm."%'";
30  $result = mysqli_query($db, $query);
31
32  $num_results = $result->num_rows;
33
34  echo "<p>Number of products found: ".$num_results."</p>";
35
36  for ($i=0; $i <$num_results; $i++) {
37     $row = $result->fetch_assoc();
38     echo "<p><strong>".($i+1).". Product Name: ";
39     echo htmlspecialchars(stripslashes($row['ProductName']));
40     echo "</strong><br />Product Description: ";
41     echo stripslashes($row['Product_Description']);
42     echo "<br />Price: ";
43     echo stripslashes($row['Unit_Price']);
44     echo "</p>";
45  }
46
47  $result->free();
48  $db->close();
49
50?>

1 个答案:

答案 0 :(得分:0)

因为您的查询失败了。您需要检查返回值,并检查错误消息。

if( ! $result = mysqli_query($db, $query) ) {
    die(mysqli_error($db));
}

ABC A lways B e C hecking [您的返回值]