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 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题