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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵