Reputation: 8339
I am stuck into a problem in PHP. Basically I need to show data fetched from mysql table in a HTML table in certain format. Am unable to figure out how I can do it. Below is my query and PHP code:
$array = array();
$query = mysql_query("select name, townid, entry_date from tbl_entry where month(entry_date) = '02' and year(entry_date) = '2016' group by townid, name ");
while($row = mysql_fetch_array($query)) {
$array[$row['name']][$row['townid']]= $row['entry_date'];
}
With this, var_dump on $array variable shows correct mysql results that is expected. Here is the content of $array:
array (size=2)
B =>
array (size=2)
3 => string '2016-02-16' (length=10)
6 => string '2016-02-16' (length=10)
A =>
array (size=1)
3 => string '2016-02-16' (length=10)
I need to display this in a HTML table in below format:
Serial Number | Date | A | B
-------------------------------------------------------
1 | 2016-02-16 | 3 | 3
2 | 2016-02-16 | | 6
Code tried so far:
<thead>
<tr>
<th>Sr No</th>
<th>Date</th>
<?php
foreach($demo3 as $srid=>$array) {
$SRname = GetSingleRow(ADMIN,$srid);
echo "<th>".$SRname['name']."</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
$count = 1;
foreach($array as $key=>$val) {
echo "<tr>";
echo "<td>$count</td>";
foreach($val as $t =>$d) {
echo "<td>".$d[$t]."</td>";
}
echo "</tr>";
$count++;
}
?>
</tbody>
But am not getting expected output. Please help me in this.
Upvotes: 0
Views: 670
Reputation: 103
Try read somesthing about PDO — its improve ypu skills with DB work. Try this code:
<?php
$rowArray = array();
foreach( $array AS $key => $val )
{
$i = 0;
foreach( $val AS $key2 => $val2 )
{
$rowArray[ $i ][ 'date' ] = $val2;
$rowArray[ $i ][ $key ] = $key2;
$i++;
}
}
?>
<thead>
<tr>
<th>Sr No</th>
<th>Date</th>
<?php
foreach($demo3 as $srid=>$array) {
$SRname = GetSingleRow(ADMIN,$srid);
echo "<th>".$SRname['name']."</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach( $rowArray AS $row )
{
echo '<tr>';
echo '<td>' . $i . '</td>';
foreach( $row AS $rowData )
{
echo '<td>' . $rowData . '</td>';
}
echo '</tr>';
$i++;
}
?>
</tbody>
Upvotes: 1