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

报告相同问题?