1

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();
}
2
  • As told there is nothing wrong with your code, but the table is empty. Commented Dec 22, 2017 at 10:25
  • Can you verify that your table actually contains data? The code seems fine to me. Commented Dec 22, 2017 at 10:53

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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());

3 Comments

todos table is not empty :/
Thanks Bro It Work
If I read this question right, which you closed as duplicate, it is asking about inserting into database, not fetching. The question you linked to is about fetching.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.