PHP show table from record with same id - php

I want to return to the user a table that shows his orders but when a user orders one product the table is ok but in the moment that orders 2 product they get 2 lines with the same ID but different ProductID same total price.
$email = strval($_SESSION["email"]);
$TabellaOrdini = "SELECT DISTINCT ordini.IDOrdini, clienti.Indirizzo,
clienti.Nome, clienti.Cognome, ordini.StatoConsegna,
prodotti.Descrizione, ordini.TotaleOrdine,
pacco.IDProdotti, pacco.Quantita
FROM (((clienti NATURAL JOIN ordini)
JOIN pacco ON ordini.IDPacco = pacco.IDPacco)
JOIN prodotti ON pacco.IDProdotti = prodotti.IDProdotti)
WHERE clienti.IDClienti = ordini.IDClienti
AND clienti.Email = '$email'
ORDER BY ordini.IDOrdini";
$CheckOrdini = "SELECT insertphpordini.IDOrdini,
concat(insertphpordini.Descrizione,' x ',insertphpordini.Quantita) AS Risultato
FROM insertphpordini
WHERE insertphpordini.Email = '$email'
AND insertphpordini.IDOrdini IN
( SELECT insertphpordini.IDOrdini
FROM insertphpordini
GROUP BY insertphpordini.IDOrdini
HAVING COUNT(IDOrdini)>1
)";
$result = $conn -> query($TabellaOrdini);
$result2 = $conn -> query($CheckOrdini);
echo "<table id='customers'>";
echo "<tr><th colspan=7>Ordini</th></tr>";
echo "<tr>";
echo "<td><b>IDOrdine</b></td>";
echo "<td><b>Nome</b></td>";
echo "<td><b>Cognome</b></td>";
echo "<td><b>Indirizzo</b></td>";
echo "<td><b>Stato Consegna</b></td>";
echo "<td><b>Prodotto</b></td>";
echo "<td><b>Totale Ordine</b></td>";
while($row = $result -> fetch_assoc()) {
echo "<tr>";
echo "<td> $row[IDOrdini]</td>";
echo "<td> $row[Nome]</td>";
echo "<td> $row[Cognome] </td>";
echo "<td> $row[Indirizzo] </td>";
echo "<td> $row[StatoConsegna] </td>";
echo "<td> $row[Descrizione] / $row[Quantita]</td> ";
echo "<td> $row[TotaleOrdine]€ </td>";
echo "</tr>";
}
echo "</table>";
the query $TabellaOrdini get all values from a user whit that email and the query $CheckOrdini get only the values with the same ID and concat the Description and quantity as Risultato.
My goal is that is possible to have 1 order with 1 ID and in Product(row 6 from left of the table) have "ProductName1/Quantity1, ProductName2/Quantity2"

Use GROUP_CONCAT() to combine values from multiple rows into a single column.
$TabellaOrdini = "SELECT ordini.IDOrdini, clienti.Indirizzo, clienti.Nome, clienti.Cognome, ordini.StatoConsegna,
prodotti.Descrizione, ordini.TotaleOrdine, GROUP_CONCAT(pacco.IDProdotti, '/', pacco.Quantita) AS Prodotto
FROM clienti
NATURAL JOIN ordini
JOIN pacco ON ordini.IDPacco = pacco.IDPacco
JOIN prodotti ON pacco.IDProdotti = prodotti.IDProdotti
WHERE clienti.IDClienti = ordini.IDClienti AND clienti.Email = '$email' ORDER BY ordini.IDOrdini
GROUP BY ordini.IDOdini";
It's also not necessary to group your joins with ().
And you should stop substituting variables directly into SQL, and instead use prepared statements with bind_param().

You can use better display of Orders with Order ID, Customer details, Date in one row along with a drop down with all detailed products and quantities. This way you are not limited with tabular display option.
Else, you can use GROUP_CONCAT with ordini.IDOrdini (your OrderID) and display products as "product01, product02, product03" for same Order01 for instance.
Here some link for data-tables with child-rows :
https://datatables.net/examples/api/row_details.html
Or you can ajax it out for large child product sets :
https://datatables.net/blog/2017-03-31
NOTE: Please ensure PHP security and try to follow some design pattern for a clean code. Look for Database Object and Binding input parameters with $conn->prepare [https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php]

Related

Changing cell value based on another cell

I am working on a simple php app where I store employees data.
Basically, I have in MySQL few tables, one of them is Employees where I have many columns like name, position, costcenter, manager, etc...
Via php I am able to change the records in the table (simple CRUD).
What I want to achieve is when I change Position based on this Cost Center to be changed.
I have a separate table (CostCenters.sql) with all positions and their cost centers with a structure like this:
CostCenter
Position
124
Engineer
199
Manager
In my edit.php I am taking the positions from this table like this:
echo "<select name='position' required>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT position
from employees
WHERE id = $id
UNION SELECT jobtitle from costcenters");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['position'] ."'>"
.$data['position'] .
"</option>";
}
echo "</select>";`
In the same file for cost centers I have:
echo "<select name='costcenter' required>";
//echo "<option disabled selected>-- Избери --</option>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT costcenter, POSITION
FROM employees
WHERE id = $id
UNION ALL SELECT constcenternr, jobtitle
FROM costcenters ");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['costcenter'] ."'>"
.$data['costcenter'] . "-" .$data['POSITION'] . "
</option>";
}
echo "</select>";`
And my update query is very simple:
UPDATE employees
SET costcenter ='$costcenter',idcard ='$idcard',
personalnr ='$personalnr',position ='$position';
The question is how to make it when I update the record for Position to automatically changed also the CostCenter based on the value corresponding from (CostCenters.sql).
I have tried editing the select query for edit.php to union also the records from (CostCenters.sql) but had no success.
Here is my select query: (simple)
$result = mysqli_query($mysqli,
"SELECT * FROM employees WHERE id ='$id' ");
while($data = mysqli_fetch_array($result))
My first trial was to modify update query in this way:
UPDATE employees
SET costcenter =
(select costcenternr
from CostCenters
where ****),idcard ='$idcard',
personalnr = '$personalnr',position = '$position';
Frankly speaking, my SQL skills are not enough to complete this query

Join issue for two tables

I can not get Select to work properly. I'm fairly familiar putting img src and have used loops before but the select is stumping me.
I have two tables. TableA (Aid, Aname, Adescription) TableB (Bid, Bimagefile, Aid). TableB holds multiple images which belong to TableA Aid. There may be 5 images for one Aid and 3 images for another Aid.
How can I write the Select and Join so I only see images related to 1 TableA Aid? I have the following
$query = "SELECT TableB.Bid, TableB.Bimagefile, TableA.Aname
FROM TableB
INNER JOIN TableA ON TableB.Aid = TableA.Aid";
but the results are a complete list of all Aname and their matching Bimagefile. I need to have the result show for one Aid. Help please.
$stmt = $con->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
if($num>0){
echo "<table class='table table-hover table-responsive table-
bordered'>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Image</th>";
echo "</tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td>{$Aname}</td>";
echo "<td>{$Bimagefile}</td>";
echo "</tr>";
}
echo "</table>";
}

MySQL Selecting A Key From A Seperate Table

I am currently fetching data from a group of location MySQL tables here is what I currently have
$query = "SELECT Name, CountryCode, Population FROM City WHERE (Population > '6000000') ORDER BY Population DESC";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>$row[0]</td>";
echo "<td>$row[1]</td>";
echo "<td>$row[2]</td>";
echo "</tr>\n";
}
mysql_close($link);
The thing I am trying to figure out is how to convert the CountryCode to the actual country. Here is how I would call the country table to get the name
SELECT Name FROM Country WHERE Code = 'CountryCode';
How would I combine these two statements into one?
EDIT: Here is what I got to work. Is this considered a JOIN?
$query = "SELECT a.Name, a.CountryCode, a.Population, b.Code, b.Name FROM City a, Country b WHERE (a.CountryCode = b.Code) AND (a.Population > '6000000') ORDER BY Population DESC";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>$row[0]</td>";
echo "<td>$row[2]</td>";
echo "<td>$row[4]</td>";
echo "</tr>\n";
}
mysql_close($link);
U need to join City table and Country table having one primary key and one foreign key.
Read about Natural Join. It's easy.
You can use this query:
$query = "SELECT city.Name,country.Name,city.CountryCode,city.Population from city INNER JOIN country where country.CountryCode=city.CountryCode and city.population>5000 ORDER BY city.Population DESC";
This is working fine.

How can i simplify this php mysql count code and reduce queries?

I have database with 8 different product category for download.
pic, app, ebo, tem, des, cod, mus, cat
I'd like to count clients total downloaded products and total downloads of each product category.
Maximum daily limit downloads for category product is 3.
When user log in should see how many downloads remain.
Here is working code
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." products.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'pic'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ." downloaded pictures";
$leftovers = 3 - $row['sum'];
echo " $leftovers pictures remain for download";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'app'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ."downloaded applications";
$leftovers = 3 - $row['sum'];
echo " $leftovers applications remain for download.";
echo "<br />";
}
$query = "SELECT CO.... This procedure repeat eight times for different product category.
result
You have downloaded 12 products.
3 downloaded pictures 0 pictures remain for download.
1 downloaded applications 2 applications remain for download.
3 downl.......
You could use a GROUP BY statement to group your results.
SELECT COUNT(`Product`) AS `Sum`, `Product`
FROM `service_downloads`
WHERE `client_id` = '<client_id>'
GROUP BY `Product`
Then you can use one while statement to loop through each product:
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['Sum'] ."downloaded " . $row['Product'];
$leftovers = 3 - $row['Sum'];
echo " $leftovers " . $row['Product'] . " remain for download.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum,product FROM service_downloads where client_id like '$client' GROUP BY product";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." ".$row['product'];
echo "<br />";
}
This should work
You should breakdown the quantity of downloads per category in one query:
SELECT product,COUNT(*)
FROM service_downloads
WHERE client_id like '$client';
I also don't think you need to use LIKE; you probably want to use =
You can get a single result set with all the sums in it with this query.
SELECT COUNT(*) as sum, product
FROM service_downloads
WHERE client_id = '$client'
AND PRODUCT IN ('pic', 'app', 'abc', 'def', 'ghi')
GROUP BY product WITH ROLLUP
ORDER BY product NULLS FIRST
This will give you one row for each specific product and a summary (rollup) row with a NULL value in the product column.
If this query takes a long time create an index on (client, product) and it should go pretty fast.
If you are showing this data frequently, which is what it sounds like, then you should have a separate table that represents those SUMs and is index by CLIENT_ID.
You can then increment/decrement that value each time you add a new entry.
For example, when you add a new row to service_downloads with an entry in 'pic' for CLIENT_ID 1, then you would also increment this shortcut table:
UPDATE service_counts SET pic=pic+1 WHERE client_id=1;

MySQL/PHP Count

I have 2 MySQL tables, one for storing albums and the other for songs. I am displaying a list of albums in a table, and I want to be able to add a column called songs to display the number of songs in this album. The way I have it now just messes up my table:
Thanks for everyone's help!
Assuming that "playlist" is what you consider an album and the first while loop iterates on playlists, I'd rewrite your code like this:
while($row = mysql_fetch_array($rs)) {
echo "<tr>\n";
echo "<td>".$row['playlist_id']."</td>";
// Assuming playlist_id is an integer value in your database
$query = "
SELECT Playlist_id, COUNT(Playlist_id) AS songCount
FROM ws_music
WHERE Playlist_id = ". intval ($row['playlist_id']) ."
GROUP BY Playlist_id
";
$result = mysql_query($query) or die(mysql_error());
// No need for the second while loop
$row2 = mysql_fetch_array($result);
echo "<td>There are ". $row2['songCount'] ." ". $row2['Playlist_id'] ." song.</td>";
echo "</tr>";
}

Categories