dounieqi6959 2013-07-26 06:49
浏览 29
已采纳

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

I am learning PHP and MySQL from 'PHP and MySQL web dev'. Currently I am finding difficulties in displaying results from database. Here is the code:

<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>

When I run the above code, this is the error i get.

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

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • dongyuan2388 2013-07-26 06:54
    关注

    There's probably an error in your SQL query and $result is false instead of the result object.

    I think it's probably because you're missing some spaces in the query. This line:

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

    should be something like:

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

    It would help if we knew the values of:

    $_POST['searchtype'];
    $_POST['searchterm'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记