dongrong8972 2013-04-17 16:33
浏览 89
已采纳

Php Preparement语句回显查询结果

Just for you all to know, im starting to learn PDO so dont get mad at me :)

When i was using mysqli i would do this get the result from a query and echo something:

$query2= "SELECT acess FROM statistic WHERE id_page IN(SELECT id FROM page WHERE title='".$registos1['title']."')";
        $result2 = mysqli_query($ligaBD,$query2);
        $registos2 = mysqli_fetch_array($result2);

        if($registos2['acess']==0){
            echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>...</title></head><body>This page is private.</body></html>';exit;

And now im trying to do it on PDO but im not shure if it is like is:

$sql = "SELECT acess FROM statistic WHERE id_page IN(SELECT id FROM page WHERE title=?)";
        $stm = $ligaBD->prepare($sql);
        $stm->execute(array($acess));
        $stm->fetchColumn();

        if(($row = $stm->fetch(PDO::FETCH_ASSOC))){
            echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Easy Page Builder</title></head><body>This page is private.</body></html>';exit;
        }

This if($registos2['acess']==0){ does the same thing as this if(($row = $stm->fetch(PDO::FETCH_ASSOC))){ ?

What is the value returned from fetch(PDO::FETCH_ASSOC) ? I have read that is boolean but im not shure if this is even the proper code to use to get the result from the query like i was doing in the past when using mysqli.

Thanks.

  • 写回答

2条回答 默认 最新

  • drasebt1835 2013-04-17 16:35
    关注

    No. it doesn't. You've missed one step in your PDO code. You fetch a row, but then don't look at what you fetched. It should be more like:

        $stm->execute(array($acess));
        $row = $stm->fetch(PDO::FETCH_ASSOC);
        if ($row['access'] == 0) {
           ...
        }
    

    As your code is written, you fetch a row result, but use that row result in a basic if(). If data was retrieved, $row will be some non-empty data, and PHP casts it to boolean TRUE, meaning you get the 'access denied' message. This will happen even if the actual results of the query say "access granted" because you're not looking at the resulting data from the query, you're just testing if ANY data was returned AT ALL.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用Thoony写ESP32温湿度检测无源蜂鸣器报警代码?
  • ¥20 部件内部的CT图像数据集
  • ¥15 Visual studio调用动态库
  • ¥15 双目摄像头标定后的校准文件
  • ¥15 powerbi举证增加度量值后出现对应关系错乱
  • ¥30 频率分析法分析绘制奈奎斯特图、波特图
  • ¥15 弹出来一万个系统找不到指定的文件框框,怎么解决
  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow