I have a multidimensional array returned from PHP fetchAll()
function like this:
$sql="SELECT * FROM users ORDER BY id ASC LIMIT 10";
$stmt = $db->prepare($sql);
$stmt->execute();
$numcolumn = $stmt->columnCount();
$res = $stmt -> fetchAll();
IT RETURNS an array like this.
Array
(
[0] => Array
( [0] => 1
[id] => 1
[1] => Firstname one
[firstname] => Firstname one
[2] => Lastname one
[lastname] => Lastname one
)
[1] => Array
(
[0] => 1
[id] => 1
[1] => Firstname one
[firstname] => Firstname one
[2] => Lastname one
[lastname] => Lastname one
)
[2] => Array
(
[0] => 1
[id] => 1
[1] => Firstname one
[firstname] => Firstname one
[2] => Lastname one
[lastname] => Lastname one
)
)
How can I print this data in a html table like this in PHP with loop?
<table>
<th>
<td>id</td>
<td>firstname</td>
<td>lastname</td>
</th>
<tr>
<td>1</td>
<td>Firstname one</td>
<td>Lastname one</td>
</tr>
</table>
Note that the keys and values both are from the database, not static. Please help.
EDITED :
IT is for keys (not working) :
$keys = array_keys($res);
for($i = 0; $i < 1 ; $i++) {
foreach($res[$keys[$i]] as $key => $value) {
$msg.="<th style='background-color:red;'>";
$msg.= $key; //will store column name of the table to msg variable
$msg.="</th>";
}}
$msg.="</tr>";
$i=0;
$count=1; //used to print sl.no
it is for values(working) :
foreach($res as $row){
$msg.="<tr><td>".$count."</td>";
for($i=0;$i< $numcolumn;$i++)
{
$var=$row[$i]; //will store all the values of row
$msg.="<td style='white-space: nowrap;word-break: keep-all;'>".$var."</td>";
}
$count=$count+1;
$msg.="</tr>";
}
$msg.="</table>";
echo $msg;
ANSWER :
$res = $stmt -> fetchAll(PDO::FETCH_ASSOC);
$msg="<table><tr><th style='white-space: nowrap;background-color:red;'>Serial No.</th>";
// for keys:
$keys = array_keys($res);
for($i = 0; $i < 1 ; $i++)
{
foreach($res[$keys[$i]] as $keyg => $value)
{
$msg.="<th style='background-color:red;'>";
$msg.= $keyg; //will store column name of the table to msg variable
$msg.="</th>";
}
}
$msg.="</tr>";
$i=0;
$count=1; //used to print sl.no
//for values
foreach($res as $row => $key)
{
$msg.="<tr><td>".$count."</td>";
foreach($key as $C=>$d)
{
$var = $d;
$msg.="<td style='white-space: nowrap;word-break: keep-all;'>".$var."</td>";
}
$count=$count+1;
$msg.="</tr>";
}
$msg.="</table>";
echo $msg; //for printing table in html