Fatal error: Call to a member function fetchAll() on a non-object in pdo

前端 未结 4 1405
日久生厌
日久生厌 2020-12-21 18:40

I\'m new to pdo just tried the following and getting fatal error.

$pdo = new pdo(\'mysql:localhost;widget_corp;charset=utf-8\', \'root\', \'\');
$query = $pd         


        
相关标签:
4条回答
  • 2020-12-21 19:32

    PDO::query return false if your query is wrong.

    SELECT * FROM 'users'

    should be

    SELECT * FROM `users`
    
    0 讨论(0)
  • 2020-12-21 19:35

    Use this code instead:

    $pdo = new PDO('mysql:host=localhost;dbname=widget_corp;charset=UTF-8', 'root', '');
    $query = $pdo->query("SELECT * FROM `users`");
    $result_array = $query->fetchAll(PDO::FETCH_ASSOC);
    

    If this doesn't work, are you sure that PDO is installed properly?

    0 讨论(0)
  • 2020-12-21 19:37

    Change:

    mysql:localhost;widet_corp
    

    to

    mysql:host=localhost;dbname=widget_corp
    

    Also in your posted code:

    $query = $pdo->query("SELECT * FROM 'users'");
    

    you have the table name inside single quotes. In Mysql you should use a backtick instead for tables and columns.

        $query = $pdo->query("SELECT * FROM `users`");
    
    0 讨论(0)
  • 2020-12-21 19:43

    $pdo->query() will return false if the query fails. You're not initiating the pdo correctly, and you probably want to check if the query didn't return an error, so:

    $pdo = new pdo('mysql:host=localhost;dbname=widget_corp;charset=utf-8', 'root', '');
    $query = $pdo->query("SELECT * FROM `users`");
    if($query !== false)
    {
        $result_array = $query->fetchAll(PDO::FETCH_ASSOC);
    }
    
    0 讨论(0)
提交回复
热议问题