为什么这个查询不返回一个对象?

时间:2013-07-26 06:49:44

标签: php mysql database

我正在从PHP和MySQL网络开发中学习PHP和MySQL。目前我发现显示数据库结果有困难。这是代码:

<body>
    <?php
        $searchtype = $_POST['searchtype'];
        $seachterm = trim($_POST['searchterm']);

        if(!$searchtype || !$seachterm){
            echo "You did not enter all the details. Bye";
            exit;
        }

        if(!get_magic_quotes_gpc()){
            $searchtype = addslashes($searchtype);
            $seachterm = addslashes($seachterm);
        }

        @ $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');

        if(mysqli_connect_errno()){
            echo "Sorry Could not connect to db";
            exit;
        }

        $query = "select * from books where".$searchtype."like '%".$seachterm."%'";

        $result = $db -> query($query);

        $num_of_results = $result->num_rows; // Line 47

        echo "Num of books found is ".$num_of_results." ";

        for($i = 0; $i < $num_of_results; $i++){
            $row = $result -> fetch_assoc();
            echo "<p><strong>".($i+1).". Title: ";
            echo htmlspecialchars(stripslashes($row['title']));
            echo "</strong><br />Author: ";
            echo stripslashes($row['author']);
            echo "<br />ISBN: ";
            echo stripslashes($row['isbn']);
            echo "<br />Price: ";
            echo stripslashes($row['price']);
            echo "</p>";
        }

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

当我运行上面的代码时,这就是我得到的错误。

Notice: Trying to get property of non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 47
Num of books found is
Fatal error: Call to a member function free() on a non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 64

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您的SQL查询可能存在错误,而$resultfalse而不是结果对象。

我认为这可能是因为你在查询中遗漏了一些空格。这一行:

$query = "select * from books where".$searchtype."like '%".$seachterm."%'";

应该是这样的:

$query = "SELECT * FROM books WHERE '" .$searchtype. "' LIKE '%".$seachterm."%'";

如果我们知道以下内容的价值会有所帮助:

$_POST['searchtype'];
$_POST['searchterm'];

答案 1 :(得分:1)

您没有检查以确保$result符合您的想法。您的查询很可能出现问题,$db->query()的返回值为false。最好检查一下,以确保您的查询确实有效。

尝试使用此代码:

$result = $db->query($query);
if ($result === false) {
        // Query failed - we can't continue
        die('My query failed, I want to be a teapot instead.');
}

// Now it's safe to operate on $result, deal with a successful query, but no results
if ($result->num_rows == 0) {
       echo 'no results found.';
       // display any other output, search again?
       exit;
}

// At this point you have results to display

现在,至于您的查询失败的原因,请仔细阅读本部分:

"select * from books where".$searchtype."like '%"

你需要一些空间。如果$searchtype是'foo',您的查询实际上会扩展为:

 select * from books wherefoolike 

尝试改为:

"select * from books where ".$searchtype." like '%"

注意'where'之后和'like'之后的空格?这应该可以解决它。

我不会过分强调确保你的查询准备好安全,你的书应该考虑到这一点 - 但请记住这一点。