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

折月煮酒 提交于 2019-11-28 11:04:50

问题


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'];
}

回答1:


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'];
}



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/12126193/pdo-call-to-a-member-function-fetch-on-a-non-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!