How to display combined rows in the database table with same ID - php

i have a question for the experts. I have no idea how to combine all the order ID with the same ID,
like in the picture, all orders with order ID = 1 are in one transaction, how do i combine all order IDs with the same id and display only one total price for all of the proudcts bought. and since all order ID are the same so the deliver and payment option will also be the same just need to display one row.
and a follow up question is how will i also show all the products bought if i combine all the same order IDs, compute the total price and display delivery and payment option in one single row
Here is the picture for my database relationship, i just followed the ones on the internet. the only difference is that "products" are changed to "inventory" and "serial" in products are changed to "prod_id"
here are my codes to display the current picture.
<?php
session_start();
$conn = #mysql_connect("localhost","root","");
$db = #mysql_select_db("");
$qry = "SELECT customers.name,customers.payment,customers.carrier, orders.date, order_detail.productid, order_detail.quantity, order_detail.price, order_detail.orderid, inventory.prod_name
FROM customers
RIGHT JOIN orders on customers.serial=orders.serial
RIGHT JOIN order_detail on orders.serial=order_detail.orderid
LEFT JOIN inventory on order_detail.productid=inventory.prod_id where customers.email='{$_SESSION['email']}'";
mysql_set_charset("UTF8");
$result = #mysql_query($qry);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
echo "<center>";
echo "<table class='CSSTableGenerator'>
<tr>
<td>Date of Purchase</td>
<td>First Name</td>
<td>Order ID</td>
<td>Products</td>
<td>Quantity</td>
<td>Total Price</td>
<td>Delivery Option</td>
<td>Payment Option</td>
<tr>";
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['orderid']."</td>";
echo "<td>".$row['prod_name']."</td>";
echo "<td>".$row['quantity']."</td>";
echo "<td>".($row['price']*$row['quantity'])."</td>";
echo "<td>".$row['carrier']."</td>";
echo "<td>".$row['payment']."</td>";
echo "</tr>";
}
echo "</table>";
?>
</table>

It seems that what you're needing to learn for this particular question is the SQL Group By clause.
This (untested, might need minor tweaking) should do the trick. Note that you don't get order item quantities out of this, but I would say that it's possible to get them.
SELECT o.date, c.name, o.serial as 'Order Id', GROUP_CONCAT(p.name) as 'Products', SUM(od.price) as 'Total', c.carrier, c.payment
FROM orders o
JOIN customers c on o.customer_id = c.serial
JOIN orderdetail od on o.serial = od.orderid
JOIN products p on od.productid = products.prod_id
GROUP BY o.serial
Of particular note is a handy aggregate function in MySQL called GROUP_CONCAT.
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

Related

MAX and COUNT sql query

I need to know how to use MAX() and COUNT() query to display the "fiser" table entries that contain the primary "codp" key that comes from the "products" table, depending on a previously selected period?
Table products : codp, denp ;
Table orders: codc,codp ;
Table returns : codr, datar, codc, codp
<?php
if(isset($_POST['add'])){
$sql = "SELECT p.denp, a.datar,MAX(p.codp)
FROM ( SELECT COUNT(p.codp) FROM products p ) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d') ";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
echo "
<table border=1 >
<tr>
<td><p> ".$row['codp']." </p></td>
<td><p> ".$row['denp']." </p></td>
<td><p> " .$row['codr']." </p></td>
<td><p> " .$row['datar']." </p></td>
<td><p> " .$row['codc']." </p></td>
</tr> </table> ";
}
} else {
echo " No results!" ;
}
}
?>
You should use group by for codp and the join the related result eg:
$sql = "SELECT p.denp, r.datar,MAX(p.cnt_codp)
FROM (
SELECT codp, COUNT(*) as cnt_codp FROM products
group by codp
) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d')
GROUP BY p.denp, r.datar ";
and you should check for your db driver for param bindig instead of use of php var in sql (you are at risk for sql injection)
and you should also use a group by for not aggreated column or reeval the question if you need the values related to max result (the use of aggregation function without a proper group by columns for not aggreagated is depreacted in sql ai the most recent version of mysql is not allowed)

Display which areas are available in a booking system php

I'm really struggling with some php code. It's for an assignment at university. I'm designing a booking system for vip areas within a nightclub. I want to be able to show the available areas in a table so then I can select that area and proceed to book that area for the date searched.
Basically I've managed to write some code and I think I'm getting there but I'm just a little stuck now. I've attached the availablebooking.php file which I want to be able to pull the areas from the database that aren't currently booked for the date searched. What I've tried to do is pull the area_id and room_name where the area_id is not in the booking table on the date searched, resulting in the areas that are displayed all being available. But the code I've managed to write displays the opposite, so it displays the rooms that are booked, not the rooms that are available.
Just looking for some guidance.
availablebooking.php
$Criteria = $_POST ['criteria'];
$query = "SELECT Area.Area_id, Room.Room_name FROM Booking_details
INNER JOIN Area ON Area.Area_id=Booking_details.Area_id
INNER JOIN Room ON Room.Room_id=Area.Room_id
INNER JOIN Booking ON Booking_details.Booking_id=Booking.Booking_id
WHERE Booking.Date != $Criteria";
$result = mysqli_query($dbcon, $query) or die("Error getting data");
echo "<table>";
echo "<tr> <th> Area</th> <th> Room </th>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>";
echo $row['Area_id'];
echo "</td><td>";
echo $row['Room_name'];
echo "</td></tr>";
}
SELECT a.Area_id
, r.Room_name
FROM Booking_details d
JOIN Area a
ON a.Area_id = d.Area_id
JOIN Room r
ON r.Room_id = a.Room_id
LEFT JOIN Booking b
ON d.Booking_id = b.Booking_id
AND b.Date = '$Criteria'
WHERE b.date IS NULL;
Or something like that

Displaying Data From 4 (Four) Tables in Mysql

I just need a simple queries actually,
Here are my tables:
Information -> id_info, year, information_name, person_name, country_id, state_id, city_id
Country -> id, country_id, country_name
State -> id, state_id, country_id, state_name
City -> id, city_id, state_id, city_name
I have runs some queries, for example's:
SELECT *
FROM information, country, state, city
WHERE information.country_id =country.country_id
AND information.state_id = state.state_id
AND information.city_id = city.city_id
GROUP BY information.id_info;
My Simple Scripts:
echo '<td>'.$data['country_name'].'</td>
echo '<td>'.$data['state_name'].'</td>
echo '<td>'.$data['city_name'].'</td>
$data-> Is my while script with $query=mysql_query...
from the queries above only displaying two (2) data's from my database, but in the database it has five (5) data's.
Then I've trying to delete the Group statement, but the data kept looped and displaying almost 8000 data's, but I only got 5 data on tables.
I've tried everything, left join, right join, inner join....
I need help, I know it's quite simple, but how can I just display all the data normally.
Thanks.
Here My Full Scripts for displaying the data:
<table cellpadding="5" cellspacing="0" border="1">
<tr bgcolor="#CCCCCC">
<th>No.</th>
<th>Year</th>
<th>Information Name</th>
<th>Person Name</th>
<th>Country</th>
<th>State</th>
<th>City</th>
<th>Act</th>
</tr>
<?php
include('connect.php');
$query = mysql_query("SELECT *
FROM information
INNER JOIN country ON information.country_id =country.country_id
INNER JOIN state ON information.state_id = state.state_id
INNER JOIN city ON information.city_id = city.city_id
GROUP BY information.country_id, information.state_id, information.city_id") or die(mysql_error());
if(mysql_num_rows($query) == 0){
echo '<tr><td colspan="6">No data!</td></tr>';
}else{
$no = 1;
while($data = mysql_fetch_assoc($query)){
echo '<tr>';
echo '<td>'.$no.'</td>';
echo '<td>'.$data['year'].'</td>';
echo '<td>'.$data['information_name'].'</td>';
echo '<td>'.$data['person_name'].'</td>';
echo '<td>'.$data['country_name'].'</td>';
echo '<td>'.$data['state_name'].'</td>';
echo '<td>'.$data['city_name'].'</td>';
echo '<td>Detail / Edit / Delete</td>';
echo '</tr>';
$no++;
}
}
?>
You can use INNER JOIN assuming that index key is properly used:
SELECT country.country_name,
state.state_name,
city.city_name
FROM information
INNER JOIN country ON information.country_id = country.country_id
INNER JOIN state ON information.state_id = state.state_id
INNER JOIN city ON information.city_id = city.city_id
Try changing your GROUP BY and use INNER JOIN :
SELECT *
FROM information
INNER JOIN country ON information.country_id =country.country_id
INNER JOIN state ON information.state_id = state.state_id
INNER JOIN city ON information.city_id = city.city_id
GROUP BY information.country_id, information.state_id, information.city_id
It worked now, *sigh the problem is the table in information, I have to empty the table first.
It quite a lot happened to me, the records was the problem source's, I've been through this a lot. Thank you guys for the help, now it's work perfectly fine.
The two answer above worked perfectly, Thank you.

While loop Repeats infinitely

I have a while loop that populates a dropdown box with values from a mysql table. There are only two matching records and it is repeating them over and over. How do i only display each record once?:
$query = "SELECT * FROM members, sportevents, dates, results, event, userlogin ".
"INNER JOIN members AS m ON userlogin.id = m.id " .
"WHERE userlogin.username = '$un' " .
"AND sportevents.id = members.id " .
"AND sportevents.event_id = event.id " .
"AND sportevents.date_id = dates.id " .
"AND sportevents.result_id = results.id";
echo "<form method='POST' action='display.php'>";
echo "Please Select Your Event<br />";
echo "<select name='event'>";
echo "<option>Select Your Event</option>";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo "<option>";
echo $row['eventname'];
echo "</option>";
}
echo "</select>";
echo "<input type='submit' value='Go'>";
echo "</form>";
Have you tried running that query manually in the mysql monitor? Nothing in your code would produce an infinite loop, so most likely your query is not doing joins as you expect and is doing a cross-product type thing and creating "duplicate" records.
In particular, your query looks very suspect - you're using the lazy "from multiple tables" approach, instead of explicitly specifying join types, and you're using the members table twice (FROM members ... and INNER JOIN members). You don't specify a relationship between the original members table and the joined/aliased m one, so most likely you're doing a members * members cross-product fetch.
give that you seem to be fetching only an event name for your dropdown list, you can try eliminating the unused tables - ditch dates and results. This will simplify things considerable, then (guessing) you can reduce the query to:
SELECT event.id, event.eventname
FROM event
INNER JOIN sportevents ON event.id = sportevents.event_id
INNER JOIN members ON sportevents.id = members.id
INNER JOIN userlogins ON members.id = userlogins.id
WHERE userlogins.username = '$un'
I don't know if the members/userlogins join is necessary - it seems to just feed sportevents.id through to members, but without knowing your DB's schema, I've tried to recreate your original query as best as possible.
You could always try changing the SELECT statement to a SELECT DISTINCT statement. That'll prevent duplicates of the selected fields.
Either that or reading all the results before displaying them, then de-duping them with something like array_unique().
Checkout My Example. It will be helped for you to understand. Because this code 100% working for me. Study it and get a solution.
And You Should Use DISTINCT keyword and GROUP BY Keyword. That's the Main Thing to prevent repeating values.
<?php
$gtid = $_GET['idvc'];
if(isset($_GET['idvc']))
{
$sql = mysql_query("SELECT DISTINCT gallery_types.gt_id, gallery_types_category.gtc_id, gallery_types_category.gt_category, gallery_types_category.gtc_image FROM gallery_types, gallery_types_category WHERE $_GET[idvc]=gtid GROUP BY gt_category");
mysql_select_db($database,$con);
while($row = mysql_fetch_array($sql))
{?>
<table>
<tr>
<td width="100px"><?php echo $row['gt_id'] ?></td>
<td width="100px"><?php echo $row['gtc_id'] ?></td>
<td width="300px"><?php echo $row['gt_category'] ?></td>
<td width="150px">
<a href='view_all_images.php?idvai=<?php echo $row[gtc_id] ?>' target='_blank'>
<img width='50' height='50' src='<?php echo $row[gtc_image] ?>' />
</a>
</td>
</tr>
</table>
<?php
}
}
?>
Better Understand, Follow Following Method,
$sql = mysql_query("SELECT DISTINCT table1.t1id, table2.t2id, table2.t2name FROM table1, table2 WHERE t1id=t2id GROUP BY t2name");

Using while() display even with NULLS

I have a table and I am displaying its contents using PHP and a while(); I have about three fields in the table that are NULL but can be change, but I want them to still display all the results in my table.
But, it only shows the records with data in EVERY field. Anyone how I can display it? I get a count of the table and it gives me 2, but only displays one.
<h3>Viewing All Updates</h3>
<h4>Below are all active updates for COTC</h4>
<table>
<thead>
<tr>
<th>Site Name</th>
<th>Page</th>
<th>Flag</th>
<th>Date Sent</th>
<th>View</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT sname,page_name,date_submitted,u_id,clients.c_id,flag,completed FROM updates INNER JOIN clients ON updates.c_id = clients.c_id INNER JOIN pages ON updates.page = pages.p_id ORDER BY date_submitted DESC";
$query = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($query)){
$completed = $row['completed'];
if($completed == 1){
print '<tr class="quiet">';
}else{
print '<tr>';
}
print '<td>'.$row['sname'].'</td>';
print '<td>'.$row['page_name'].'</td>';
print '<td>'.$row['flag'].'</td>';
print '<td>'.$row['date_submitted'].'</td>';
print '<td class="center"><img src="images/page_edit.png" alt="Edit entry!" /></td>';
print '</tr>';
}
?>
</tbody>
</table>
Your PHP is correctly printing every row returned. I believe your problem is in the query.
SELECT sname,page_name,date_submitted,u_id,clients.c_id,flag,completed
FROM updates INNER JOIN clients ON updates.c_id = clients.c_id
INNER JOIN pages ON updates.page = pages.p_id
ORDER BY date_submitted DESC
This query will only return a row in updates if it has a matching one in clients and a matching one in pages. If you want the clients or the pages joins to be optional (a updates row that has c_id or page of NULL will still return) change them from INNER JOINs to LEFT JOINs.

Categories