doulong6761 2012-05-17 17:36
浏览 8
已采纳

为什么我的PDO不工作?

I am starting to use PDO and I successfully connected to MySQL using PDO. However, when I try to SELECT stuff from my DB, nothing happens. Nothing is echoed. (even though I have records in that table, and the column username exists) No error in my PHP log.

I am using MAMP and all PDO components seem to be working in phpinfo() (since I was able to connect to db in the first place)

Please let me know what could have gone wrong. Thanks a lot

    <?php
    try 
    {
        $connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
                              'xxxxxxx');   


            $stmt=$connection->prepare("SELECT * FROM users");
            $stmt->execute();

            while ($row=$stmt->fetch(PDO::FETCH_OBJ)){

                echo $row->username;
            }

    }

    catch(Exception $e)
    {
        echo "There was an error connecting to the database";
    }

    ?>
  • 写回答

4条回答 默认 最新

  • duanbin4847 2012-05-17 17:40
    关注

    You need to tell PDO that you want it to throw exceptions:

    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    Following your comment below, it is apparent that your DSN is incorrect. It should be:

    $connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
    

    Note that the syntax is dbname= rather than dbname: (which you had originally).

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度