I am trying to create a 'run sheet' of doughnut orders from a ZenCart database. I read a dozen posted questions to get to [Jeff Lee's response to question]: SQL query to rebuild a table using its dynamic row data for column names. Since I am using MySQL, I think I need to generate a dynamic query because my 'ProductName' data changes.
I have written the following code which generates an HTML table similar in structure to the example database table but I do not know how to incorporate his solution into my code as I am not starting with a database table but rather a query result-set.
I am going to try creating a database table from my existing query in order to use Jeff's solution but I think the preferred method would be to incorporate his code into my query, I just don't know how.
I am using PHP/5.6.11 and MySQL/5.6.25
<?php
echo 'Attempt connection to the [donutsdb] database';
print '<br />';
require("includes/connect2donutsdb.php");
?>
<?php
//this script will query the 'orders' and 'orders_products' tables
//and combine the information based on the 'orders_id' field
//I added aliases to improve the query readability
try {
echo '[donutsdb]';
print '<br />';
$query = "
SELECT
o.orders_id AS 'O_OID', o.customers_name AS 'O_CName',
p.products_name AS 'P_PName', p.products_quantity AS 'P_PQuant'
FROM
orders AS o
INNER JOIN orders_products AS p
ON o.orders_id=p.orders_id
";
//first pass just gets the column names
print "<table> \n";
$result = $dbh->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr> \n";
foreach ($row as $field => $value){
print " <th>$field</th> \n";
} // end foreach
print " </tr> \n";
//second query gets the data
$data = $dbh->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr> \n";
foreach ($row as $name=>$value){
print " <td>$value</td> \n";
} // end field loop
print " </tr> \n";
} // end record loop
print "</table> \n";
print '<br />';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
?>
My code generates an HTML table with the following structure:
O_OID | O_CName | P_PName | P_PQuant
1 | mark | Glazed | 12
2 | John | Glazed | 8
2 | John | Bavarian Cream | 4
3 | mark | Chocolate Dipped | 12
4 | Kevin | Donut Holes | 10
5 | Kevin | Peanut Butter | 1
5 | Kevin | Blueberry | 2
What I am trying to achieve is:
O_OID | O_CName | Glazed | Bavarian Cream | Chocolate Dipped | Donut Holes | Peanut Butter | Blueberry
1 | mark | 12 | 0 | 0 | 0 | 0 | 0
2 | John | 8 | 4 | 0 | 0 | 0 | 0
3 | mark | 0 | 0 | 12 | 0 | 0 | 0
4 | Kevin | 0 | 0 | 0 | 10 | 1 | 2