Changing cell value based on another cell - php

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

Related

PHP show table from record with same id

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]

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;

What is an SQL query for counting records that are existing more than once in a database?

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("students");
$id = $_POST['id'];
$grade = $_POST['grade'];
$query = "INSERT INTO `st_table` (`St_id`,`Grade`) VALUES ('$id','$grade')";
$result = mysql_query($query);
$query = "SELECT * from `st_table`";
$result = mysql_query($query);
echo "<table>";
echo "<th>St_id</th><th>Grade</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['St_id'] . "</td><td>" . $row['Grade'] . "</td></tr>";
}
This code adds values into a table both ID and Grade. I want another query that will be able to count how many As, Bs, Cs, etc. and OUTPUT it on an html table.
Here, Your query is ok just group by Grade not Grades
"SELECT `Grade`, COUNT(*) AS count FROM `st_table` GROUP BY `Grade`";
Here is sqlfiddle
After edit
The query i am mentioning should work for you, you can check fiddle for that as for as you modified code is concerned you have to change your table a bit since you are going to include St_id as well so make it 3 column and correspondingly change query too.

How to insert into a table after doing a select in a form

I have a PHP form that is collecting information and writing it to a database and it is working correctly. I have one field that is a select to choose entries from an existing table. I would like that result to be inserted into a different table but can't get the insert into to work. I would like to insert the FacilityName field chosen in the select to table2.
$result = mysql_query("SELECT * FROM facility");
print "<select name=\"Id\" > \n";
while ($row = mysql_fetch_array($result)){
$Id = $row['Id'];
$FacilityName = $row['FacilityName'];
print "<option value=$Id>$FacilityName\n";

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