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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?