2

我正在从“PHP and MySQL web dev”学习 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

我究竟做错了什么?

4

2 回答 2

2

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

我认为这可能是因为您在查询中缺少一些空格。这一行:

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

应该是这样的:

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

如果我们知道以下各项的价值,将会有所帮助:

$_POST['searchtype'];
$_POST['searchterm'];
于 2013-07-26T06:54:05.813 回答
1

您没有检查以确保这$result是您认为的那样。您的查询很可能出现问题,返回值为$db->query()is 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”之前的空格吗?那应该可以解决它。

我不会过多地强调确保您的查询已为安全做好适当的准备,您的书应该涉及到这一点 - 但请记住这一点。

于 2013-07-26T07:09:04.650 回答