Reputation: 10771
I have the below syntax that is used to display a MySQL query in PHP:
function get_dayssincecapture($db)
{
$result = $db->query("SELECT DATEDIFF(now(), sarrive)as days,count(loadnumber) as loads from v2loads where adminstatus='captured' group by DATEDIFF(now(), sarrive) ");
return $result;
}
$dayssincecapture = get_dayssincecapture($db);
Display Syntax:
<table border=1>
<tr>
<? while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) { ?>
<td><? echo $row['days']; ?><br><? echo $row['loads']; ?></td>
<? } ?>
</tr>
</table>
this produces the below screen output
How do I alter by table syntax in order to get the days field as a row heading and the load field as the second row of my table?
so what I want will be:
Thanks as always,
Upvotes: 1
Views: 2063
Reputation: 358
You can try:
<?php
while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) {
$days_row .= "<td>" . $row['days'] . "</td>";
$loads_row .= "<td>" . $row['loads'] . "</td>";
}
?>
<table>
<tr>
<td>Days</td>
<?php echo $days_row; ?>
</tr>
<tr>
<td>Loads</td>
<?php echo $loads_row; ?>
</tr>
</table>
Upvotes: 1
Reputation: 247650
If you wanted to perform this type of transformation in MySQL, then you will be pivoting the data. MySQL does not have a pivot function but you can replicate this using an aggregate function with a CASE
statement:
select
count(case when DATEDIFF(now(), sarrive) = 1 then loadnumber end) as Day_1,
count(case when DATEDIFF(now(), sarrive) = 2 then loadnumber end) as Day_2,
count(case when DATEDIFF(now(), sarrive) = 3 then loadnumber end) as Day_3,
count(case when DATEDIFF(now(), sarrive) = 4 then loadnumber end) as Day_4,
count(case when DATEDIFF(now(), sarrive) = 5 then loadnumber end) as Day_5,
count(case when DATEDIFF(now(), sarrive) = 6 then loadnumber end) as Day_6,
count(case when DATEDIFF(now(), sarrive) = 7 then loadnumber end) as Day_7
from v2loads
where adminstatus='captured'
You can also write this code inside of a prepared statement to create this dynamically since the values will be unknown.
Upvotes: 1
Reputation: 152206
Try with:
<?php
$dayssincecapture = get_dayssincecapture($db);
$data = array('days' => array(), 'loads' => array());
while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) {
$data['days'][] = $row['days'];
$data['loads'][] = $row['loads'];
}
?>
<table style="border: 1px solid #000">
<tr>
<td>Days</td>
<?php foreach ( $data['days'] as $day ) { ?>
<td><?php echo $day; ?></td>
<?php } ?>
</tr>
<tr>
<td>Loads</td>
<?php foreach ( $data['loads'] as $load ) { ?>
<td><?php echo $load; ?></td>
<?php } ?>
</tr>
</table>
Upvotes: 5