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 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路