-6

I got fatal error

Fatal error: Uncaught Error: Call to a member function fetch() on boolean in C:\xampp\htdocs\sonu\PDO\test.php:7 Stack trace: #0 {main} thrown in C:\xampp\htdocs\sonu\PDO\test.php on line 7

$db = new PDO('mysql:host=localhost;root', 'test', '');

$query = $db->query("SELECT * FROM sonu");

while($row = $query->fetch())
{
    print_r($row);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135

1 Answers1

0

Your PDO constructor is wrong. You are not declaring the database to which the PDO instance should connect to.

$db = new PDO('mysql:host=localhost;root', 'test', '');

The DSN should have the database name and the host name. You have root at the end of it which should not be there.

The line above should be like so:

$db = new PDO('mysql:host=localhost;dbname=dbnamehere', 'test', '');

Have a look at the documentation in the future and check that your code corresponds with it.

MinistryOfChaps
  • 1,458
  • 18
  • 31