There is such code:

$db = new PDO('mysql:host=localhost;dbname=table','root','12345'); $d = $db->query("SELECT * FROM order"); foreach($d as $d2){ echo $d2['name']; } 

The problem is that foreach gives an error.
print_r($d) empty.
Data bd (host, bd name, user, password) are correct. What is missing here?

    3 answers 3

    There is not enough error reporting.

    after line

     $db = new PDO('mysql:host=localhost;dbname=table','root','12345'); 

    you should always write one

     $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); 

    and after that, the PDO will begin to report why it was not possible to get the data.

      The fetch method is missing.

      For example, you can extract the data like this:

       $statement = $db->query('SELECT name FROM order'); while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { echo $row['name'] . "\n"; } 

      All records can also be fetched using the fetchAll method.

      Well, to add an exception for errors would be nice:

       $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

      Total, the following code will turn out:

       try { $db = new PDO('mysql:host=localhost;dbname=table','root','12345'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $statement = $db->query("SELECT * FROM order"); foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $item) { echo $item['name'] . <br>; } } catch (PDOException $e) { // Обработка исключений... } 
      • one
        The PDOStatement class implements the Traversable interface. So using fetch is not necessary at all - Dmitriy Simushev
      • @DmitriySimushev, thanks for the info. My answer is not quite correct. - sleeper
      • Writing catch if you don’t know what to do inside is also not worth it - Ipatiev

      To check the variables use var_dump() it displays all data types since so how do you get the object, call fethAll () and go through foreach

       $db = new PDO('mysql:host=localhost;dbname=table','root','12345'); $d = $db->query("SELECT * FROM order"); foreach($d->fethAll() as $d2){ echo $d2['name']; }