MySQL query with PHP and WHERE specification - php

With this update query if the id is in chk_list then I set checked=1. I want if the id isn't in the list to set chk_list=0
$update = "UPDATE data SET checked=1 WHERE id IN($chk_list)";
$qry = $db->query($update);
Is there any simple way after WHERE to set if?

You can use IF() function to determine value to be set. Do the following:
$update = "UPDATE data SET checked = (IF(id IN ($chk_list), 1, 0))";
$qry = $db->query($update);
Note: Please use Prepared Statements to prevent SQL injection related issues

If you want to explicitly set checked as 1 or 0, then the if should be in the set area
Notice that its very dangerous to update all of the table to the extent that MySQL by default prevents this from happening, ans you should set safe updates to 0
UPDATE data SET checked = IF(id IN ($chk_list), 1,0)

What about this with CASE? Not sure pretty neat or not but seems it'll work :)
UPDATE data SET checked=
CASE
WHEN id IN ($chk_list) THEN 1
WHEN id NOT IN ($chk_list) THEN 0
END

Related

Can I use DECLARE as an SQL statement in PHP

I am trying to execute a query in PHP, but this code wouldn't work for some reason, it doesn't detect the keywords at all(DECLARE, SELECT, WHERE). Is there anything I can do and after all can I even use DECLARE in PHP as a mySQLi statement.
$sql2 ="DECLARE #MaxID INT; SELECT #MaxID = MAX(productID) FROM products; UPDATE sunglasses SET sunglassesId = #MaxID WHERE sunglassesId = 0;";
After all I am trying to update a field in Table1 where its initial value is 0 with a value from a field in Table2.
Hope that made sense.
P.S tried this query in Microsoft SQL Management studio and it worked, in PHP it doesnt.
change your query to this and you don't need any other variable:
UPDATE sunglasses
SET sunglassesId = (SELECT MAX(productID) FROM products)
WHERE sunglassesId = 0;

Leave current value if var is empty in a UPDATE query (sql)

I want not update a record when the variable is empty when executing a UPDATE query in SQL. However, when the variable is filled, the record should be updated.
So in example, the myAge field in the database have currently a value of 20 (type int).
After executing the following query, the record should still be 20.
$age = '';
db_con->query("UPDATE info SET myAge = ".$age." WHERE account_id = 1");
Ps: I know I could check if the variable is empty with PHP, but I was wondering If this could be archieved within SQL?
You could use an IF construct in SQL to check if the value is empty:
$age = mysql_real_escape_string($age);
db_con->query("UPDATE info SET myAge = IF('".$age."' = '', myAge, ".$age.") WHERE account_id = 1");
If the passed PHP variable is empty, you set the old myAge.
Checking in PHP makes more sense, you might save a database query.
The way you are passing that variable to your database is potentially dangerous. If you didn't know about mysql_real_escape_string, look it up NOW.
Better yet, start using a database wrapper that escapes values for you.
I would add the condition into the where, if you only care about one field.
It is not clear what you mean by empty. That could be either NULL or a blank string. My guess is that myAge is a number, so NULL would be "empty":
UPDATE info
SET myAge = ".$age."
WHERE account_id = 1 AND myAge IS NOT NULL;
You can also do this in the SET, if you like:
UPDATE info
SET myAge = (CASE WHEN myAge IS NOT NULL THEN ".$age." END)
WHERE account_id = 1;
This is necessary if you have multiple columns that you want to update like this. I much prefer CASE over IF(), because CASE is ANSI standard and available in most databases.

Using a SELECT Query to look up a UPDATE Query on MySQL

I'm using a SELECT query to obtain a variable using mysql_fetch_assoc. This then puts the variable into an UPDATE variable to put the returned value back into the database.
If I hard code the value, or use a traditional variable and it goes in just fine, but it doesn't work when using a value previously retrieved from the database. I've tried resetting the array variable to my own text and that works.
$arrgateRetrivalQuery = mysql_query(**Select Query**);
$arrGate = mysql_fetch_assoc($arrgateRetrivalQuery);
$arrivalGateTest = $arrGate['gatetype'];
$setGateAirportSQL = "UPDATE pilots SET currentgate = '".$arrivalGateTest."' WHERE pilotid = '".$pilotid."'";
$setGateAirportQuery = mysql_query($setGateAirportSQL);
// Close MySQL Connection
mysql_close($link);
This will just make the field to update have nothing in it, however whenever I remove the variable from the SELECT to one I define, array or not, it will work.
Hope this is clear enough. Thanks in advance.
Is arrivalGateTest a number or a string? How did you try to put another value in the query? If you are sure the previous query returns a value, try to write: $setGateAirportSQL = "UPDATE pilots SET currentgate = '$arrivalGateTest' WHERE pilotid = '$pilotid'";.
Just change your sql to inlcude a subquery.
You could use the following general syntax:
UPDATE pilots SET currentgate = (SELECT gate FROM airport WHERE flight='NZ1') WHERE pilotid='2';
which is demonstrated on this fiddle
This saves the extra query and more accurately describes what you are trying to achieve.
WARNING - test it carefully first!

UPDATE sql query and get the updated field in one single query

I'm trying to update a value of a column using the codeigniter query function like this:
$this->db->query("UPDATE table SET val = val + 1 WHERE name = 'xxxxx');
Is there any way to get the result of this update in the same query function? I have to do a select query in order to do it and it's dangerous because of the amount of users this application is managing.
If there is another query in between the update and the select, the result would not be correct.
Thanks!
Use transaction and for update. This is an example from zend, which is a similar kind of db accessing thing:
$db->beginTransaction();
$val = $db->select()->forUpdate()->from('table', 'val')->orderBy('val DESC')->limit(1)->query()->fetchColumn();
$db->update('table', 'val = '.($val+1), 'name = "xxx"');
$db->commit()
The for-update with the transaction prevents another query interfering.
Learn more about for update here: http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
and about codeigniter transactions here: http://ellislab.com/codeigniter/user-guide/database/transactions.html (thanks to #Nanne for that)

mysql_affected_rows(); does not work for checking if row exists

i am using mysql_affected_rows() to check if i have to enter new record or update existing, but the problem is if the user tries to enter exactly same data as record which already exists it runs insert into.
$result = mysql_query("update Data set Score='$score',Comment='$_POST[Comments]' where Date='$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]' AND User='$_POST[UserID]';");
$last = mysql_affected_rows();
if ($last==0) {
$result1 = mysql_query("INSERT INTO Data (User,Date,Score,Comment) VALUES ('$_POST[UserID]','$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]','$score','$_POST[Comments]')");
what should i do to avoid redundant entries
You could parse mysql_info() output (but the solution itself will be affected by race condition issue)
You could create unique key User + Date and end up with a single query using ON DUPLICATE KEY UPDATE syntax:
INSERT INTO `Data` (User,Date,Score,Comment)
('$_POST[UserID]','$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]','$score','$_POST[Comments]')
ON DUPLICATE KEY UPDATE Score='$score',Comment='$_POST[Comments]'
some solutions:
add another query to see if data exists, and then decide if you want to do some action (update/delete) or nothing.
add a 'modified' column with type "TIMESTAMP" and make it on update - CURRENT_TIMESTAMP
i'd go with first option.
btw, you should escape your post data (mysql_real_escape_string) to prevent injects or malformed query string
You may get the number of affected rows with FOUND_ROWS() instead of mysql_affected_rows(). The latter counts the not modified rows as well.
$result = mysql_query("update Data set Score='$score',Comment='$_POST[Comments]' where Date='$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]' AND User='$_POST[UserID]';");
$last = mysql_query("SELECT ROW_COUNT();");
$last = mysql_fetch_array($last);
...
Reference: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count

Categories