PDO - Call to a member function fetch() on a non-o

2019-01-29 07:39发布

My error:

( ! ) Fatal error: Call to a member function fetch() on a non-object in C:\wamp\www\PDO\index.php on line 13

My code:

<?php 

$config['db'] = array(
    'host'      =>      'localhost',
    'username'  =>      'root',
    'password'  =>      '',
    'dbname'    =>      'learnpdo'
);

$db = new PDO('mysql:host='.$config['db']['host'].';dbname'.$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$query = $db->query("SELECT articles . title FROM articles");

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    echo $row['title'];
}

I know there are many questions like this, but none of the answers seem to work.

Thanks


EDIT:

Above is fixed, thanks to everyone below. :) Now I'm getting another error:

Notice: Undefined index: id in C:\wamp\www\PDO\index.php on line 7

Here is my database:

http://d.pr/i/vcod

Here is my code:

$db = new PDO('mysql:host=localhost;dbname=learnpdo;charset=UTF-8', 'root', '');
$query = $db->query("SELECT `articles`.`title` FROM `articles`");

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    echo $row['id'];
}

3条回答
Juvenile、少年°
2楼-- · 2019-01-29 08:17

Instead of:

$query = $db->query("SELECT articles . title FROM articles");

Try:

$query = $db->query("SELECT title FROM articles");

edit

Try:

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    echo $row['title'];
}
查看更多
你好瞎i
3楼-- · 2019-01-29 08:17

This error almost always means that your query didn't work the way you wanted it to, and as a result $query is null (or false?) and not a query result object. Try echoing db->errorinfo() and see if it tells you what went wrong.

You can also try pasting the text of your query into mysql directly and seeing what the result is. If that appears to work correctly, then the problem might be with your database connection code.

查看更多
叛逆
4楼-- · 2019-01-29 08:23

PDO::query() returns false (which obviously is a non-object) if the query fails. So that's your problem. Your query has an error.

I recommend you to set the error mode in PDO.

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

and then catch the error to see what is wrong with your query.

The different error modes that exist is PDO::ERRMODE_SILENT, PDO::ERRMODE_WARNING and PDO:ERRMODE_EXCEPTION. You can read about them in the PHP manual on PDO. Knowing how to debug when writing SQL is important and the key to not having to ask these kind of questions.

About your other problem

You gotta select the id column if you want to use it.

SELECT * FROM articles

or

SELECT id, title FROM articles
查看更多
登录 后发表回答