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:
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'];
}
Instead of:
Try:
edit
Try:
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.
PDO::query()
returnsfalse
(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.
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
andPDO: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.
or