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
Related
i want to fetch multiple columns of mysql table for each unique id and echoing the result in a single row of a HTML table for each unique id.I am getting the result in the following form from the table ..
userid | date | status
------------------------------------
1 | 28-06-17 | 1
------------------------------------
1 | 29-06-17 | 2
------------------------------------
1 | 30-06-17 | 0
------------------------------------
2 | 28-06-17 | 1
------------------------------------
2 | 29-06-17 | 2
------------------------------------
2 | 30-06-17 | 3
------------------------------------
Here is the code..just a basic php code to get the record from database..
if($con)
{
$query="SELECT * FROM `usersDetail` WHERE userid='$_POST["user_id"]'";
$result=mysqli_query($con, $query);
while($rowusersDetail=mysqli_fetch_assoc($result))
{
echo $rowusersDetail['userid']."<br>";
echo $rowusersDetail['date']."<br>";
echo $rowusersDetail['status']."<br>";
}
}
*what i want is to generate html table using PHP to display all the Records of a
particular user into a single row..
userid | 28-06-17 | 29-06-17 | 30-06-17
_________________________________________
1 | 1 | 2| 0
_________________________________________
2 | 1 | 2| 3
_________________________________________
kindly please Help..thanks
This is can be done with the help of foreach loop.
For that you need to retrieve all data at a time then you can manipulate the data with your requirement.
You can do like this
If your data is like
$data=[['userid'=>1,'date'=>'21-03-2017','status'=>2],
['userid'=>2,'date'=>'21-03-2017','status'=>1],
['userid'=>1,'date'=>'22-03-2017','status'=>6],
['userid'=>2,'date'=>'22-03-2017','status'=>7],
['userid'=>1,'date'=>'24-03-2017','status'=>2],
['userid'=>2,'date'=>'24-03-2017','status'=>6]];
Then
$finalData=[];
foreach ($data as $stats){
$finalData[$stats['userid']][$stats['date']]=$stats['status'];
}
foreach ($finalData as $id=>$value){
echo 'userId->'.$id;
echo '<br>';
foreach ($value as $date=>$status){
echo $date.' -> '.$status; echo '<br>';
}
echo '<br>';
}
It will give out put as
I thing it will work for you.
I have a table that contains Aspiring team for particular positions and various vote casted.
The data is below
Teamtable
| no | team | position | votes Cast |
| 1 | A | President | 2 |
| 3 | B | President | 1 |
| 4 | C | Secretary | 2 |
| 6 | D | Secretary | 1 |
I want to be able to get this in an html format using php and mysql just as below
EXPECTED VIEW IN THE HTML AND PHP FORMAT
PRESIDENT
Team | Total Votes | Percentage |
A | 2 | 66.67 |
B | 1 | 33.33 |
SECRETARY
Team | Total Votes | Percentage |
C | 2 | 66.67 |
D | 1 | 33.33 |
This is what i have tried so far
//QUERY
$SQL=SELECT
`team`,
`position`,
`votesCast`
FROM
Teamtable
$Results=$db->query($SQL);
$data=array();
while($row=mysqli_fetch_assoc($Results)){
$team=$row['team'];
$position=$row['position'];
$totalVote=$row['votesCast'];
$data[$position][]=$position;
$data1[$position][]=$team;
$data2[$position][]=$totalVote;
}
foreach($data as $position =>$electionResults){
$teams=$data1[$position];
$totalVotes=$data2[$position];
foreach($teams as $re => $teas){
$votes=$totalVotes[$re];
echo "
<table>
<tr>
<td>$teas</td>
<td>$votes</td>
</tr>
</table>";
}
}
I have to tried up to this point, any help is appreciated.
This could be very helpful for you
while($row = mysqli_fetch_assoc($result)) {
$data[$row['position']]['total'][]=$row['votes'];
$data[$row['position']][]=$row;
}
foreach($data as $k=>$v){
echo '<p>'.$k.'</p>';
echo '<table border="1">';
$total_votes=array_sum($v['total']);
foreach($v as $kk=>$vv){
if($kk!=='total'){
$percentage=round($vv['votes']/$total_votes*100,2);
echo '<tr><td>'.$vv['tean'].'</td><td>'.$vv['votes'].'</td><td>'.$percentage.'%</td></tr>';
}
}
echo '</table>';
}
You wan't to have the table on the outside of the foreach.
echo "<table>";
foreach($teams as $re => $teas){
$votes=$totalVotes[$re];
echo "<tr>
<td>$teas</td>
<td>$votes</td>
</tr>";
}
echo "</table>";
I have put a script together which prints all of the rows from the "sales_list" table but only those with the "users_sales_guild_id" which matches the logged in user. This works fine.
What I am trying to do is print all of the rows but retrieve the matching sales_id from the "accessories_orders" table, and put the "accessories_orders_total" and shipped status with the query, so the query below should look like this in the browser if the person logging in has a "user_sales_guild_id" value of "1234".
+--------+---------------+-------------------+----------+
| Model | Customer Name | Accessories Total | Status |
+--------+---------------+-------------------+----------+
| Nissan | Malcom Smith | | Add |
| Ford | Jane Smith | 200.00 | Pending |
+------------------------+-------------------+----------+
So if there is a matching row in the "accessories_orders" table, then it will print the "shipped" and "accessories_orders_total" data. If there is no matching row for this, then it will display an "Add" link which leads to the add_accessories_sales.php.
I'm getting an error message "Undefined index: sales_model" and pretty much everything else within the first query, can anyone point out where I am going wrong?
"sales_list" Table
+--------------------------------------------------------------------------------------------------------------------------+
| sales_list |
+------+--------------------------+--------------------------+------------------------+-------------+----------------------+
| sales_id | users_sales_guild_id | sales_customer_firstname | sales_customer_surname | sales_model | sales_entry_date |
+----------+----------------------+--------------------------+------------------------+-------------+----------------------+
| 1 | 1234 | Jane | Smith | Ford | 2013-12-02 12:00:00 |
| 2 | 5678 | John | Chan | Mazda | 2013-12-03 12:00:00 |
| 3 | 5678 | Kevin | Chan | Fiat | 2013-12-04 12:00:00 |
| 4 | 1234 | Malcom | Smith | Nissan | 2013-12-05 12:00:00 |
+----------+----------------------+--------------------------+------------------------+-------------+----------------------+
"accessories_orders" table
+-------------------------------------------------------------------------------------------------------------------------+
| accessories_orders |
+-----------------------+----------------------+----------+--------------------------+-------------------------+----------+
| accessories_orders_id | users_sales_guild_id | sales_id | accessories_orders_total | accessories_orders_date | shipped |
+-----------------------+----------------------+----------+--------------------------+-------------------------+----------+
| 1 | 1234 | 1 | 200.00 | 2013-12-02 12:00:00 | Pending |
| 2 | 5678 | 2 | 350.00 | 2013-12-03 12:00:00 | Pending |
| 3 | 5678 | 3 | 100.00 | 2013-12-03 12:00:00 | Pending |
+-----------------------+----------------------+----------+--------------------------+-------------------------+----------+
EDITED and UPDATED Code
<?php
require_once ('database.php'); // Connect to the database.
$query = " SELECT sl.sales_model, sl.sales_customer_firstname, sl.sales_customer_surname, ao.accessories_orders_total, ao.shipped,
COALESCE(ao.shipped)
FROM sales_list sl
LEFT JOIN accessories_orders ao ON(ao.sales_id = sl.sales_id)
WHERE sl.users_sales_guild_id ='".$_SESSION['users_sales_guild_id']."'
ORDER BY
".$order_by." LIMIT ".$start.", ".$display;
$result = #mysql_query ($query); // Run the query.
echo '<table width="610" cellspacing="1" cellpadding="5" style="font-size:11px;">
<tr>
<td align="center">Model </td>
<td align="center">Customer Name</td>
<td align="center">Accessories Total</td>
<td align="center">Status</td></tr>';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$status = $row['shipped'];
$bg = ($bg=='#e1e3e6' ? '#cdcdcf' : '#e1e3e6'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="center">' . $row['sl.sales_model'] . '</td>';
echo '<td align="center">' . $row['sl.sales_customer_firstname'] . ' ' . $row['sl.sales_customer_surname'] . '</td>';
echo '<td align="center">$' . $row['acc.accessories_orders_total'] . '</td>';
$str = '<td align="center">';
if($status == 'Pending') {
$str .=' Pending</td></tr>';
}
else {
$str .='<strong>Add</strong></td></tr>';
}
echo $str;
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); //Close the database connection.
?>
Your query needs to be more like this:
SELECT sl.sales_model, sl.sales_customer_firstname, sl.sales_customer_surname, ao.accessories_orders_total, COALESCE(ao.shipped, 'Add') status
FROM sales_list sl
LEFT JOIN accessories_orders ao ON(ao.sales_id = sl.sales_id)
WHERE sl.users_sales_guild_id = 1234;
The LEFT JOIN is the key here. It allows a row to be returned with the data from sales_list even if there is no corresponding entry in accessories_orders.
See this fiddle for a working example: http://sqlfiddle.com/#!2/f7d3d/4
As others have already stated, you should be using the mysqli function set as opposed to the mysql function set.
First, you should not be including the table names. Example:
//wrong
echo '<td align="center">' . $row['sl.sales_model'] . '</td>';
//correct
echo '<td align="center">' . $row['sales_model'] . '</td>';
Second, you should not be using mysql unless you are using an outdated version of PHP. Switch to mysqli or PDO.
Third, you have no error handling to tell you whether your query is successful or not. In fact, you have the opposite of error handling, because you are trying to use the # operator to suppress your errors. Instead, you should do something like this:
//assuming you switch to mysqli
mysqli_query("SELECT acc.accessories_orders_id, acc.users_id, acc.sales_id,
acc.accessories_orders_total, acc.accessories_orders_date, acc.shipped,
acc.timestamp, sl.sales_id
FROM accessories_orders AS acc, sales_list AS sl
WHERE acc.sales_id = sl.sales_id");
if(mysqli_error()) {
throw new Exception(mysqli_error(), mysqli_errno());
}
If you do this, your mysql errors will be logged in the same place as your php errors. You will then be able to tell whether any of your trouble is coming from the query being malformed.
49I need help understanding the approach to take with a problem. I have a data base that contains the fields id, LastUpdate, member_name, member_extension (phone ext), member_account_id, queue_account_id.
| id | LastUpdate | member_name | member_extension | member_account_id | queue_account_id |
-------------------------------------------------------------------------------------------
| 1 | 2013-10-15 | John Smith | 2750 | 1195 | 1105 |
| 2 | 2013-10-15 | Bill Jones | 2749 | 1172 | 1248 |
| 3 | 2013-10-15 | Bill Jones | 2749 | 1172 | 1105 |
| 4 | 2013-10-15 | Fred Black | 2745 | 1195 | 1105 |
-------------------------------------------------------------------------------------------
My problem is I need to show in a table the member_account_id's of each member in a queue. For instance queue_account_id 1105 has member_extensions 2450, 2741 & 2745 listed, I need to show those extensions in a table cell. I'm using php and mysql to access database. How do I approach this?
EDIT: Here is the table I need to display, I have all of it working except the techs logged in part. i guess my main problem is understanding how to get the queried tech identity data into the techs logged in field.
| Queue | Calls | % total calls | answered by us| % answered by us| abandoned | % abandoned | Redirected | % Redirected | Techs Logged In |
----------------------------------------------------------------------------------------------------------------------------------------------|
| Premium | 1 | 9% | 0 | 0% | 1 | 100% | 0 | 0% | |
| Standard | 2 | 0% | 1 | 150% | 0 | 0% | 1 | 50% | |
| Queue 2 | 1 | 0% | 1 | 100% | 0 | 0% | 0 | 0% | |
| Queue 3 | 7 | 64% | 4 | 57% | 3 | 43% | 1 | 0% | |
| Totals | 11 | 100% | 6 | 55% | 4 | 36% | 1 | 9% | |
----------------------------------------------------------------------------------------------------------------------------------------------|
It's not clear whether this is a php or mysql question.
You can gather the items with a mysql query, as follows.
SELECT member_account_id, member_name,
GROUP_CONCAT(queue_account_id
ORDER BY group_account_id
SEPARATOR ', ') AS ids
FROM yourtable
GROUP by member_account_id, member_name
Are you looking for this?
SELECT queue_account_id,
GROUP_CONCAT(member_extension) member_extension
FROM table1
GROUP BY queue_account_id
Output:
| QUEUE_ACCOUNT_ID | MEMBER_EXTENSION |
|------------------|------------------|
| 1105 | 2750,2741,2745 |
| 1248 | 2749 |
Here is SQLFiddle demo
SELECT
t1.queue_account_id, GROUP_CONCAT(DISTINCT t2.member_extension) member_extensions
FROM tblname t1
INNER JOIN tblname t2 USING (queue_account_id)
GROUP BY t1.queue_account_id
This is how you would present it in your scenario:
<?php
$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('dbname');
$sql = 'SELECT
t1.queue_account_id, GROUP_CONCAT(DISTINCT t2.member_extension) member_extensions
FROM tblname t1
INNER JOIN tblname t2 USING (queue_account_id)
GROUP BY t1.queue_account_id';
$query = mysql_query($sql) or die(mysql_error());
echo '<table border="1">';
while ($rs = mysql_fetch_object($query)) {
echo '<tr>';
echo '<td>' . $rs->queue_account_id . '</td>';
echo '<td>';
echo '<ul>';
foreach (explode(',', $rs->member_extensions) as $extension) {
echo '<li>' . $extension . '</li>';
}
echo '</ul>';
echo '</td>';
echo '</tr>';
}
echo '</table>';
SOLUTION:
$sth = $conn->prepare("SELECT queue_account_id, GROUP_CONCAT( member_extension ) member_extension
FROM currentTechs
GROUP BY queue_account_id");
$sth->execute();
$sql = $sth->fetchAll(PDO::FETCH_ASSOC);
echo '<table border="1">';
try {
//$stmt = $conn->query($sql);
//$result = $sql->setFetchMode(PDO::FETCH_NUM);
foreach ($sql as $rs) {
echo '<tr>';
echo '<td>' . $rs['queue_account_id'] . '</td>';
echo '<td>';
foreach (explode(',', $rs['member_extension']) as $extension) {
echo $extension . ", ";
}
echo '</td>';
echo '</tr>';
}
echo '</table>';
}
catch (PDOException $e) {
print $e->getMessage();
}
I'm looking for an easy and quick way to print out the results of a MySQL SELECT query in PHP as preformatted text. What I would like is to be able to pass a query object to a function and get a printout of the recordset like the command line MySQL client does when running SELECT statements.
Here is an example of how I want it to look (i.e. ASCII):
+----+-------------+
| id | countryCode |
+----+-------------+
| 1 | ES |
| 2 | AN |
| 3 | AF |
| 4 | AX |
| 5 | AL |
| 6 | DZ |
| 7 | AS |
| 8 | AD |
| 9 | AO |
| 10 | AI |
+----+-------------+
It's basically for a generic import script, I am doing a SELECT query and want to display the results to the user for confirmation.
sprintf is your friend, if you must have a non-HTML fixed width output.
ETA:
//id: integer, max width 10
//code: string max width 2
$divider=sprintf("+%-10s+%-13s+",'-','-');
$lines[]=$divider;
$lines[]=sprintf("|%10s|%13s|",'id','countryCode'); //header
$lines[]=$divider;
while($line=$records->fetch_assoc()) {
//store the formatted output
$lines[]=sprintf("| %10u | %2.2s |", $line['id'],$line['code']);
}
$table=implode("\n",$lines);
echo $table;
If you want to print out immediately instead of storing the results, use printf instead- same syntax. There is a reasonable PHP (s)printf tutorial here.
function formatResults($cols, $rows) {
echo'<table>';
echo '<tr>';
foreach ($cols as $v) {
echo '<th>' . $v['field'] . '</th>';
}
echo '</tr>';
foreach ($rows as $sRow) {
echo '<tr>';
foreach ($sRow as $v) {
echo "<td>$v</td>";
}
echo '</tr>';
}
echo '</table>';
}
$qry = $pdo->query('DESCRIBE table');
$cols = $qry->fetchAll(PDO::FETCH_ASSOC);
$pdo->query('SELECT * FROM table');
$rows = $qry->fetchAll(PDO::FETCH_ASSOC);
formatResults($cols, $rows);
Untested but should work.
Edit: Missed ['field'] index ;)