Update row with data from another row in different tables - php

I am new to MySQL and not too sure how can I update row from another table while checking if logged in user is the same:
Telefonist='".$_SESSION["UserName"]."
And also I need to check if date is the same so it gets to right person on right date in a row:
log.Datum=telefonisti_podaci.Datum
here I am trying to count all 1s and enter sum from table1 to table2 in specific place.
Code:
$sql_zapis_do30 = "UPDATE telefonisti_podaci
SET `Total tura do 30` = (Select COUNT(*) `Ture do 30` from log,telefonisti_podaci WHERE `Ture do 30` is not null AND `Ture do 30`=1 AND log.Datum=telefonisti_podaci.Datum )
WHERE `Telefonist`='".$_SESSION["UserName"]."'";
CustomQuery($sql_zapis_do30);
I get error:
You can't specify target table 'telefonisti_podaci' for update in FROM clause
Thanks

I have solved it like this:
$sql_zapis_do30 = "UPDATE telefonisti_podaci
SET `Total tura do 30` = (Select COUNT(`Ture do 30`) from log WHERE `Telefonist`='".$_SESSION["UserName"]."' AND `Ture do 30`=1 AND `Datum`='".$datum_danas."')
WHERE `Telefonist`='".$_SESSION["UserName"]."' AND `Datum`='".$datum_danas."'";
And it works for now
Thanks

Related

Relational table query gives me a null value in the field 'id' in table

I am creating a query and I used the LEFT JOIN to join two tables. But I'm having trouble in getting the fb_id value from the table, it gives me an empty result. Here is my code:
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
....
....
The query above would give me a result like this :
I think that's why I don't get the fb_id value is because the last column is null. How do I get the value of fb_id from the first column? Thanks. I am really having trouble with this. I hope someone can enlightened my mind.
You should give an alias to the column in the parent table, because the column names are the same in both tables. When fetch_assoc() fills in $row['fb_id'], it gets the last one in the result row, which can be NULL because it comes from the second table.
SELECT a.fb_id AS a_id, a.*, b.*
FROM tblfeedback a
LEFT JOIN tblreply b ON a.fb_id = b.fb_id
WHERE a.fb_status = 1
ORDER BY a_id DESC
Then you can access $row['a_id'] to get this column.
More generally, I recommend against using SELECT *. Just select the columns you actually need. So you can select a.fb_id without selecting b.fb_id, and it will always be filled in.
Because you are using a left join, the 2 rows in your result set image are the rows from tblfeedback whose fb_id were not found in tblreply. We know this is true because all the tblreply columns in the result set are null.
With that said, its not real clear what you are asking for. If you are asking how you access the tblfeedback.fd_id column from your query via php, you can use the fetch_array method and use the 0 index.
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
while($row = $res->fetch_array()) {
echo "fb_id: " . $row[0] . "<br>";
}

Add MySQL Count Column to PHP/HTML Table

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

single mysql query to update quantity based on selecting quantity of another table

i have the following 2 queries that i was wondering if i can merge into a single statement.
$sql = "SELECT sale_qty FROM sale_device WHERE id = '$id' ";
and
$sql = "UPDATE device SET qty = $sale_qty WHERE id = $deviceId";
i want to run a select query to get the current quantity of a device from a row, then use that value minus one in a update query to set the new quantity, but don't allow it under 0
is this possible or advised to join? or would it be easier to just run 2 queries?
Yes. I think this does what you want:
UPDATE device
SET qty = (SELECT greatest(sale_qty - 1, 0)
FROM sale_device
WHERE id = '$id'
)
WHERE id = $deviceId
If I'm understanding your question correctly, I think this should work:
UPDATE Device D
JOIN Sale_Device SD ON D.Id = SD.DeviceId
SET D.qty = GREATEST(SD.sale_qty-1,0)
WHERE SD.Id = '$id'
This assumes the Sale_Device table has a DeviceId field.

How to Update records with field of same records using single query?

I have one user table with column name id,father_email,mother_email,email_notification and many more, now i want to update email_notification column with
father_email,mother_email I did it with multiple queries but i want to know that how to do it with single query only so it saves the execution time.
my code are as follows:
<?php
$qry="SELECT id,CONCAT(father_email,',',mother_email) as notify FROM user";
$query=mysql_query($qry);
while($row=mysql_fetch_assoc($query))
{
$qry2="UPDATE user SET email_notification='".$row['notify']."' WHERE id=".$row['id']."";
mysql_query($qry2);
}
?>
its working fine but i want to know how to do it with single query
This will update all email_notification columns for all users:
UPDATE user
SET email_notification = CONCAT_WS(',', father_email, mother_email)
(i think it's better to use CONCAT_WS that will skip null values in father_email or in mother_email)
This will replace all of them
UPDATE user AS u
INNER JOIN user AS ul ON ul.id = u.id
SET u.email_notification = CONCAT(ul.father_email,',',ul.mother_email)
UPDATE user
SET email_notification = CONCAT_WS(',', father_email, mother_email)

Update values of database with values that are already in DB

I've a database that stores data read from different sensors. The table looks like this:
[SensorID][timestampMS][value]
[Sensor1][123420][10]
[Sensor1][123424][15]
[Sensor1][123428][6554]
[Sensor1][123429][20]
What I would like to do is the following: There are some reads that are corrupted (numbers that are 6554), and I would like to Update that with the next value that is not corrupted (in the example shown below that would be 20). So, if a number is 6554, I would like to update that with the next value (in timestamp), that is not corrupted.
I was thinking on doing this in PHP, but I wonder if it's possible to do it directly with a SQL script.
Appreciate :)
You can use a correlated sub-query...
UPDATE
myTable
SET
value = (SELECT value FROM myTable AS NextValue WHERE sensorID = myTable.SensorID AND timestampMS > myTable.timestampMS ORDER BY timestampMS ASC LIMIT 1)
WHERE
value = 6554
The sub-query gets all the following results, ordered by timestampMS and takes just the first one; That being the next value for that SensorID.
Note: If no "next" value exists, it will attempt to update with a value of NULL. To get around this, you can add this to the WHERE clause...
AND EXISTS (SELECT value FROM myTable AS NextValue WHERE sensorID = myTable.SensorID AND timestampMS > myTable.timestampMS ORDER BY timestampMS ASC LIMIT 1)
EDIT
Or, to be shorter, just use IFNULL(<sub_query>, value)...
Not sure if this is valid syntax, can't test it ATM. You may need to change this to be JOINs instead of the nested subqueries, but in concept you can do something like (for SQL Server):
UPDATE t1
SET Value = ( SELECT Value
from MyTable t2
WHERE t2.SensorID =t1.SensorID
AND t2.[timestamp] =
( SELECT MIN([TimeStamp])
FROM mytable t3
where t3.sensorid = t2.sensorID
AND t3.[timestamp] > t2.[timestamp]
)
)
FROM Mytable t1
WHERE t1.value = 6554
I did a workaround based on Dems solution, and it works in Mysql:
I've created a "copy" of the sensors table like this:
drop table if exists sensors_new;
create table if not exists sensors_new like sensors;
insert into sensors_new select * from sensors;
Then I do what Dems recommended me doing, but using this new aux table in the select (to avoid the error that Mysql launches when Updating a table while doing a select in the same table).
UPDATE
sensors
SET
raw_data = (SELECT raw_data FROM sensors_new AS NextValue WHERE sensor_id = sensors.sensor_id AND timestampMS > sensors.timestampMS ORDER BY timestampMS ASC LIMIT 1)
WHERE
value = 6554
Then, just drop this auxiliar table.
I hope this helps Mysql users.

Categories