Munaf Hajir
Munaf Hajir

Reputation: 67

When Fetching Data from Database Returning Empty Array

My Question Is About Fetching Data From Database But Displaying Empty Array. I Connected DB by PDO and else you can see in code. Suggestions In Code it will great Help.

try{
  $tododb = new PDO('mysql:host = localhost;dbname = mytodo;charset=utf8','root','');  //Connect to the db
  $statement = $tododb->prepare('select * from todos');
  $statement->execute();
  var_dump($statement->fetchAll(PDO::FETCH_OBJ));
}
catch(PDOException $e){
  echo 'Exception -> ';
  var_dump($e->getMessage());
  die();
}

Upvotes: 1

Views: 847

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157828

In general, PDOStatement:fetchAll() returns an empty array in case your query returned no data.

It means that todos table is empty.

However, in your case it's both your inaccuracy with PDO credentials and insufficient error reporting. You didn't tell PDO to throw an exception in case of a database error.

As of parameters, you should never ever "decorate" them adding spaces or other unnecessary stuff.

And as of error reporting, always put PDO in Exceptuion mode so it could give you a clue.

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

$tododb = new PDO('mysql:host=localhost;dbname=mytodo;charset=utf8','root','', $options);
$statement = $tododb->prepare('select * from todos');
$statement->execute();
var_dump($statement->fetchAll());

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57121

Not sure what else may be failing, but in your connect, you need to remove the spaces around the '='

  $tododb = new PDO('mysql:host=localhost;dbname=mytodo;charset=utf8','root','');  //Connect to the db

Upvotes: 1

Related Questions