I'm just trying to loop through my DB and I get only the 1st row. this is my database PHP:
database.class.php:
<?php
$pdo = new PDO('mysql:host=localhost; dbname=testing070416', 'root', 'root1');
$statement = $pdo->query("SELECT * FROM users");
$rows = $statement->fetch(PDO::FETCH_ASSOC);
var_dump($rows);
?>
And the index.php:
<?php include ('database.class.php');?>
<table border="1">
<?php foreach ($rows as $value=>$key ){
echo '<tr><th style="color: red;">'.$value.'</th>';
echo '<td>'.$key.'</td></tr>';
}
?>
the result:
There's supposed to be 4 more IDs to loop on.
Thanks!
Use fetchAll
instead of fetch
Change from
$rows = $statement->fetch(PDO::FETCH_ASSOC);
Into
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
Then code for your index.php
<table border="1">
<?php
for($i = 0; $i == count($rows); $i++)
{
foreach($rows[$i] as $value=>$key )
{
echo '<tr><th style="color: red;">'.$value.'</th>';
echo '<td>'.$key.'</td></tr>';
}
}
?>
Difference between fetch
and fetchAll
fetch
actually fetches the next row from a result set.
fetchAll
returns an array containing all of the result set rows.
Use fetchAll instead of fetch to get all results.
Change:
$rows = $statement->fetch(PDO::FETCH_ASSOC);
To:
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);