Select query joining two tables PHP - php

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.

Related

How to dynamically use rowspan to print data in table in php and mysql?

In my program, the following query and code generate the following table like this:
+-------+---------+
|ward_id|Sub_block|
+-------+---------+
| 1 | A1 |
+-------+---------+
| 1 | B1 |
+-------+---------+
| 1 | C1 |
+-------+---------+
| 2 | D1 |
+-------+---------+
| 2 | E1 |
+-------+---------+
| 2 | F2 |
+-------+---------+
| 3 | K1 |
+-------+---------+
| 3 | G2 |
+-------+---------+
| 3 | I3 |
+-------+---------+
Here is my code that generate the above table.
if(isset($_POST["union_id"]) && !empty($_POST["union_id"]))
{
//Get all union data
$query = $mysqli->query("SELECT * FROM test_epi_table WHERE union_id = ".$_POST['union_id']);
//Count total number of rows
$rowCount = $query->num_rows;
//Display unions list
if($rowCount > 0)
{
echo "<hr>";
echo "<h3 align='center'>EPI Schedule</h3>";
echo "<table class='table table-bordered'>
<tr>
<th>Ward No</th>
<th>Sub-Block</th>
</tr>";
while($row = $query->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['ward_no'] . "</td>";
echo "<td>" . $row['sub_block_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<hr>";
}
else
{
echo "<br>";
echo "<h3 align='center'>Sorry, No Available Information!</h3>";
echo "<hr>";
}
}
Now I like to create the table like this. Mostly I think it is a rowspan task.
+-------+---------+
|ward_id|Sub_block|
+-------+---------+
| | A1 |
+ +---------+
| 1 | B1 |
+ +---------+
| | C1 |
+-------+---------+
| | D1 |
+ +---------+
| 2 | E1 |
+ +---------+
| | F2 |
+-------+---------+
| | K1 |
+ +---------+
| 3 | G2 |
+ +---------+
| | I3 |
+-------+---------+
what kind of changes do I need to add in my actual php code? Please help me out. Thanks in advance.
Use Inner query is one of the good way also you can use right outer join if you want it to be more efficient.

mySQL query to dynamically convert column data to column name

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

Sorting an array of information from another array output from SQL

I need to be retrieve multiple unique values from an array set of data. Currently they are extracted as follows :
while($row1 = mysql_fetch_array($result1))
{
echo "<tr>".
"<td>".$row1[0] . "</td>".
"<td>".$row1[1] . "</td>".
"<td>".$row1[2] . "</td>".
"<td>".$row1[3] . "</td>".
"<td>".$row1[4] . "</td>".
"<td>".$row1[5] . "</td>".
"<td>".$row1[6] . "</td>".
"<td>".$row1[7] . "</td>".
//$row1[8] is the number of hours
"<td>".$row1[8] . "</td>".
//$row1[9] is the user
"<td>".$row1[9] . "</td>";
}
As commented above, I need to accumulate the hours per user. However, I have problem sorting the array as the user value has to be unique in the array whereas the number has to keep stacking.
Really confused now. Appreciate any help offered.
EDIT : $row1[8] is an integer yes.
The sample data output table ( sorry no image) will be as follows :
------------------------------------------------------------------------------------------
Users |Telephone | Address | Postal Code | Hobbies | Interest| FB |Twitter | Insta | Hours
------------------------------------------------------------------------------------------
John | 92238726 | SG | 345322 | Running | Movies | 1 | 0 | 0 | 5
Tom | 922382134 | MY | 345212 | Soccer | Movies | 1 | 0 | 0 | 8
Jerry | 92238726 | SG | 342122 | stamps | Nil | 0 | 1 | 0 | 5
John | 92238726 | SG | 345322 | Running | Movies | 1 | 0 | 0 | 12
Jerry | 92238726 | SG | 342122 | stamps | Nil | 0 | 1 | 0 | 2
Based on the output above which was extracted with the mysql_fetch_array, I'd like to sort the information to something like the following :
Users | Total Hours
John | 17
Tom | 8
Jerry | 7
SQL CODE :
"select DISTINCT jl.refno, jl.logno, jl.attendee, jl.jobsummary, FROM_UNIXTIME(jl.date, '%d/%m/%y') AS 'Date-In', from_unixtime(jl.dateout + (15*3600), '%d/%m/%y') AS 'Date-Out', #timein := (left(jl.timein,2)*60+right(jl.timein,2)) AS 'Time-In', #timeout := (left(jl.timeout,2)*60+right(timeout,2)) AS 'Time-Out', #temp := ((dateout -date)* 24 * 60) + #timeout - #timein AS 'temp', us.username from joblog jl, projects proj, users us where jl.project ='{$value}' AND proj.id ='{$value}' AND jl.staff = us.id"
Since you are using MySQL anyway, I recommend you to do it with an SQL. It's cleaner.
Edit your query to:
SELECT users, SUM(hours) as total FROM userTable GROUP BY users ORDER BY total DESC;
UPDATE - PHP Edition:
You can do it like this in PHP.
$counters = array();
while ($row1 = mysql_fetch_array($result1)) {
$counters[$row1[9]] += $rows1[8];
}
arsort($counters);
foreach ($counters as $name => $total) {
// do your output here
}
<?php
function totalHours($user){
$result=mysql_query("select sum(hours) as total from table_name where users='".$user."'");
$row=mysql_fetch_array($result);
return $row['total'];
}
$result=mysql_query("select * from table_name group by users");
echo "</table>";
echo "<tr>
<td>User</td>
<td>Total Hours</td>
</tr>";
while($row1 = mysql_fetch_array($result1))
{
echo "<tr>".
"<td>".$row1[0]. "</td>".
"<td>".totalHours($row1[0]). "</td></tr>";
}
echo "</table>";
?>

I need to show items from a database in a table, how should I approach this?

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();
}

How to echo specific data in loop with a condition specific to the last row

For an accounting system, I'm using PHP & MySQL. I've two tables "GROUP" and "ACHEADS".
In the GROUP table, I have:
---------------------
| id (AI) | group |
---------------------
| 1 | Group 1 |
| 2 | Group 2 |
---------------------
In the ACHEADS table, I have:
-----------------------------------------
| id (AI) | ac_head | amount | j_id |
-----------------------------------------
| 1 | Something 1 | 2000 | 1 |
| 2 | Something 2 | 1000 | 1 |
| 3 | Something 3 | 5000 | 2 |
| 4 | Something 4 | 4000 | 2 |
| 5 | Something 5 | 8000 | 2 |
-----------------------------------------
I've joined the two tables as GROUP.id <<->> ACHEADS.j_id
Now I need to preview the data like this:
----------------------------------------------
Particulars | Details | Total |
----------------------------------------------
Group 1 | | |
Something 1 | 2000 | |
Something 2 | 1000 | 3000 |
----------------------------------------------
Group 2 | | |
Something 3 | 5000 | |
Something 4 | 4000 | |
Something 5 | 8000 | 17000 |
----------------------------------------------
GRAND TOTAL | | 20000 |
------------------------------------==========
Challenges
The table will be dynamic and will generate within a PHP loop (I'm
using a WHILE loop)
Remember: it's a table and if I miss echoing a td, then the table will break up
Problems
When I'm using the loop it's echoing the data on the Details td
accurately. But the sum of the details row according to j_id is also
echoing in each td
Preview here:
----------------------------------------------
Particulars | Details | Total |
----------------------------------------------
Group 1 | | |
Something 1 | 2000 | 3000 |
Something 2 | 1000 | 3000 |
----------------------------------------------
Group 2 | | |
Something 3 | 5000 | 17000 |
Something 4 | 4000 | 17000 |
Something 5 | 8000 | 17000 |
----------------------------------------------
My thoughts
If I can check whether it is the last data of the query, if isset,
then echo the total amount with it's td. (But remember the
Challenge#2)
Does it require a foreach loop?
I failed
I tried checking max(id), it works fine in SQL, but can't use it in
condition within a loop.
(If you still can't understand me, then on the second phase, I'll post my code.)
I would do 2 loops:
Fetch id from GROUP
Fetch amount from ACHEADS based on j_id
This would look something like (non-tested code):
echo '<table><tr><td>Particulars</td><td>Details</td><td>Total</td></tr>';
$total = 0;
$q1 = "SELECT id FROM `GROUP`";
$res1 = mysqli_query($q1);
while($row1 = mysqli_fetch_assoc($res1)) {
echo
$group_total = 0;
$j_id = $row1[id];
$q2 = "SELECT ac_head, amount FROM ACHEADS WHERE j_id = $j_id";
$res2 = mysqli_query($q2);
while($row2 = mysqli_fetch_assoc($res1)) {
echo '<tr><td>' . $row2[ac_head] . '</td>';
echo '<td>' . $row2[amount] . '</td></tr>';
$group_total = $group_total + $row2[amount];
$total = $total + $row[amount];
}
echo '<tr><td colspan="3" align="right">' . $group_total . '</td></tr>';
}
echo '<tr><td>GRAND TOTAL</td>';
echo '<td colspan="2" align="right">' . $total . '</td></tr>';
echo "</table>";
njk rockz!
It worked nicely. Thanks a lot, brother - it helped me a lot, I can't explain.
Here is my final code:
<tr style="background: #000; color:#fff;">
<th style="width:150px;">Particulars</th>
<th>Details</th>
<th>Amount</th>
</tr>
<tr>
<td>Opening Balance</td>
<td></td>
<td>500000</td> <!-- till not dynamic -->
</tr>
<?php
$total = 0;
$se = "SELECT * FROM group";
$res = mysql_query($se) or die (mysql_error());
while ($row = mysql_fetch_array($res))
{
?>
<tr>
<td colspan="3" style="font-weight:bold;"><?php echo $row['group']; ?></td>
</tr>
<tr>
<?php
$group_total = 0;
$se1 = "SELECT ac_head, amount FROM `acheads` WHERE `j_Id` = '".$row['id']."'";
$res1 = mysql_query($se1) or die (mysql_error());
while ($row1 = mysql_fetch_array($res1))
{
$group_total = $group_total + $row1['amount'];
?>
<td><?php echo $row1['ac_head']; ?></td>
<td><?php echo $row1['amount']; ?></td>
<td> </td>
</tr>
<?php
}
echo '<tr><td colspan="3" align="right">' . $group_total . '</td></tr>';
}
?>
</table>
</code>

Categories