Is it possible to execute the two update queries in phpmyadmin together?
Like wise
UPDATE jos_menu SET home = 0 WHERE 1;
UPDATE jos_menu SET home = 1 WHERE id = 9;
Now can we copy both these queries together and Run it on phpmyadmin sql query panel?
will it be executed?
Yes, both queries will be executed. The only additional thing you might add is transaction. Thanks to that you'll be sure that both queries executed successful:
START TRANSACTION;
UPDATE jos_menu SET home = 0 WHERE 1;
UPDATE jos_menu SET home = 1 WHERE id = 9;
COMMIT;
update jos_menu set home=case id when 9 then 1 else 0 end
this will update all rows, setting 1 to all that have id=9, and 0 to the rest
If you're not sure if some SQL will break your live site and you don't have a dev server, make a copy of the DB table and test it on that.
CREATE TABLE jos_menu_test LIKE jos_menu;
INSERT jos_menu_test SELECT * FROM jos_menu;
Based on #crozin answer I did following queries:
START TRANSACTION;
SELECT id into #idTech FROM `team` WHERE abbr = 'D19';
delete from team_dayoff where team_id = #idTech;
delete from team_layer_lease where team_id = #idTech;
delete from team_product_linker where team_id = #idTech;
delete from team where id = #idTech;
COMMIT;
Related
I have two table called tbl_users and tbl_img_status. I have column in tbl_img_status like below
id, user_id,status_text, scd_time,status,post_time
I am looking for run cron using PHP for publish post on time. So I have query like below
$results = mysqli_query($mysqli,"UPDATE tbl_img_status SET post_time=NOW(),status=1 WHERE status=0 AND scd_time<NOW()");
Now My issue is I also need to update tbl_users column called total_post. I want increase 1 in total_post of that user id which we have published with first query. I am new in PHP and MYSQL so not getting proper idea for do it. Let me know if someone can help me for it.
You can use one query to update two tables.
Try this query if that works.
I have got a hint from this. MySQL, update multiple tables with one query
UPDATE tbl_users, tbl_img_status
SET tbl_img_status.post_time=NOW(),
tbl_img_status.status=1,
tbl_users.total_post = tbl_users.total_post+1
WHERE
tbl_users.id= tbl_img_status.user_id
AND tbl_img_status.status=0 AND tbl_img_status.scd_time<NOW()
You can use Triggers for that purpose.
This would update for a specific user if the status changed from 0 to 1
DELIMITER $$
CREATE TRIGGER after_tbl_img_status_update
AFTER UPDATE
ON tbl_img_status FOR EACH ROW
BEGIN
IF OLD.status <> NEW.status AND NEW.status = 1 THEN
UPDATE tbl_users SET total_post = total_post +1 WHERE id = NEW.user_id;
END IF;
END$$
DELIMITER ;
IF you don't want to change the Database, you can use a INNER JOIN with And update both table as one.
Your php will then look like:
$results = mysqli_query($mysqli,"UPDATE tbl_users tu INNER JOIN tbl_img_status tis ON tu.id = tis.user_id SET tis.post_time=NOW(), tis.status=1, tu.total_post = tu.total_post+1 WHERE tis.status=0 AND tis.scd_time<NOW();");
I need to update a table in SQL via php.
When i log in to my database and write:
UPDATE table1
SET whatiwant = whatiwant
it updates all. That what i want.
But when i write this in PHP, it is not working.
I need to give him a Where clause to execute it and i have to loop through all entries.
UPDATE table1
SET whatiwant = whatiwant
WHERE id = '1'
I need to update all the entries. Why is it not working?
Use:
WHERE 1 = 1
to match all records.
or if there needs to be an Id on the left side use something that's impossible to match, e.g.:
WHERE Id <> -1
if you have id only positive numbers.
If you want to run update all the time write your statement without where otherwise if you want this SQL statement do 2 different behavior, you have to write a Stored Procedure with a parameter #id :
If a value pass to the parameter #id, it works well
If you pass null to that, it updates all rows without any where clause
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE SP
#id int =null
AS
BEGIN
UPDATE table1
SET whatiwant = whatiwant
WHERE (id = #id OR #id IS NULL)
END
GO
I'm using InnoDB.
I have table A
ID | DATA
1 | Something
2 | something else
table B
user_id | DATA
1 | NULL
my program reads a row from table A and updates table B, then deletes the row from table A after the update statement.
is it possible for two users (2 different concurrent sessions) to read the same row from table A? how can I avoid that?
that's my program
$core = Database::getInstance();
$q = $core->dbh->prepare("SELECT * FROM `tableA` LIMIT 1");
$q->execute();
$result = $q->fetch();
$q = $core->dbh->prepare("UPDATE `tableB` SET `data` = ? where `user_id`= ?");
$q->execute(array($result['data'],$ID));
// how to prevent a second user from reading the same row before the next statement gets executed
$q = $core->dbh->prepare("DELETE FROM `tableA` where `ID`= ?");
$q->execute(array($result['ID']));
Hope this helps and makes clear the view of what you want to achieve.
https://dev.mysql.com/doc/refman/5.0/en/internal-locking.html
You can SELECT ... FOR UPDATE which puts an exclusive lock onto the row (at least if the transaction isolation level is set to somewhat reasonable).
This only works if the storage engine of the table is InnoDB. Also you have to execute all queries inside of the same transaction (so execute BEGIN query at the beginning and COMMIT at the end).
I am trying to update fields in my DB, but got stuck with such a simple problem: I want to update just one row in the table with the biggest id number. I would do something like that:
UPDATE table SET name='test_name' WHERE id = max(id)
Unfortunatelly it doesnt work. Any ideas?
Table Structure
id | name
---|------
1 | ghost
2 | fox
3 | ghost
I want to update only last row because ID number is the greatest one.
The use of MAX() is not possible at this position. But you can do this:
UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;
For multiple table, as #Euthyphro question, use table.column.
The error indicates that column id is ambiguous.
Example :
UPDATE table1 as t1
LEFT JOIN table2 as t2
ON t2.id = t1.colref_t2
SET t1.name = nameref_t2
ORDER BY t1.id DESC
LIMIT 1
UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table)
This query will return an error as you can not do a SELECT subquery from the same table you're updating.
Try using this:
UPDATE table SET name='test_name' WHERE id = (
SELECT uid FROM (
SELECT MAX(id) FROM table AS t
) AS tmp
)
This creates a temporary table, which allows using same table for UPDATE and SELECT, but at the cost of performance.
I think iblue's method is probably your best bet; but another solution might be to set the result as a variable, then use that variable in your UPDATE statement.
SET #max = (SELECT max(`id`) FROM `table`);
UPDATE `table` SET `name` = "FOO" WHERE `id` = #max;
This could come in handy if you're expecting to be running multiple queries with the same ID, but its not really ideal to run two queries if you're only performing one update operation.
UPDATE table_NAME
SET COLUMN_NAME='COLUMN_VALUE'
ORDER BY ID
DESC LIMIT 1;
Because you can't use SELECT IN DELETE OR UPDATE CLAUSE.ORDER BY ID DESC LIMIT 1. This gives you ID's which have maximum value MAX(ID) like you tried to do. But MAX(ID) will not work.
Old Question, but for anyone coming across this you might also be able to do this:
UPDATE
`table_name` a
JOIN (SELECT MAX(`id`) AS `maxid` FROM `table_name`) b ON (b.`maxid` = a.`id`)
SET a.`name` = 'test_name';
We can update the record using max() function and maybe it will help for you.
UPDATE MainTable
SET [Date] = GETDATE()
where [ID] = (SELECT MAX([ID]) FROM MainTable)
It will work the perfect for me.
I have to update a table with consecutive numbers.
This is how i do.
UPDATE pos_facturaciondian fdu
SET fdu.idfacturacompra = '".$resultado["afectados"]."',
fdu.fechacreacion = '".$fechacreacion."'
WHERE idfacturaciondian =
(
SELECT min(idfacturaciondian) FROM
(
SELECT *
FROM pos_facturaciondian fds
WHERE fds.idfacturacompra = ''
ORDER BY fds.idfacturaciondian
) as idfacturaciondian
)
Using PHP I tend to do run a mysqli_num_rows then put the result into a variable, then do an UPDATE statement saying where ID = the newly created variable. Some people have posted there is no need to use LIMIT 1 on the end however I like to do this as it doesn't cause any trivial delay but could prevent any unforeseen actions from being taken.
If you have only just inserted the row you can use PHP's mysqli_insert_id function to return this id automatically to you without needing to run the mysqli_num_rows query.
Select the max id first, then update.
UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table)
How do I get the ID of the last updated row in MySQL using PHP?
I've found an answer to this problem :)
SET #update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT #update_id := id)
WHERE some_other_column = 'blah' LIMIT 1;
SELECT #update_id;
EDIT by aefxx
This technique can be further expanded to retrieve the ID of every row affected by an update statement:
SET #uids := null;
UPDATE footable
SET foo = 'bar'
WHERE fooid > 5
AND ( SELECT #uids := CONCAT_WS(',', fooid, #uids) );
SELECT #uids;
This will return a string with all the IDs concatenated by a comma.
Hm, I am surprised that among the answers I do not see the easiest solution.
Suppose, item_id is an integer identity column in items table and you update rows with the following statement:
UPDATE items
SET qwe = 'qwe'
WHERE asd = 'asd';
Then, to know the latest affected row right after the statement, you should slightly update the statement into the following:
UPDATE items
SET qwe = 'qwe',
item_id=LAST_INSERT_ID(item_id)
WHERE asd = 'asd';
SELECT LAST_INSERT_ID();
If you need to update only really changed row, you would need to add a conditional update of the item_id through the LAST_INSERT_ID checking if the data is going to change in the row.
This is officially simple but remarkably counter-intuitive. If you're doing:
update users set status = 'processing' where status = 'pending'
limit 1
Change it to this:
update users set status = 'processing' where status = 'pending'
and last_insert_id(user_id)
limit 1
The addition of last_insert_id(user_id) in the where clause is telling MySQL to set its internal variable to the ID of the found row. When you pass a value to last_insert_id(expr) like this, it ends up returning that value, which in the case of IDs like here is always a positive integer and therefore always evaluates to true, never interfering with the where clause. This only works if some row was actually found, so remember to check affected rows. You can then get the ID in multiple ways.
MySQL last_insert_id()
You can generate sequences without calling LAST_INSERT_ID(), but the
utility of using the function this way is that the ID value is
maintained in the server as the last automatically generated value. It
is multi-user safe because multiple clients can issue the UPDATE
statement and get their own sequence value with the SELECT statement
(or mysql_insert_id()), without affecting or being affected by other
clients that generate their own sequence values.
MySQL mysql_insert_id()
Returns the value generated for an AUTO_INCREMENT column by the
previous INSERT or UPDATE statement. Use this function after you have
performed an INSERT statement into a table that contains an
AUTO_INCREMENT field, or have used INSERT or UPDATE to set a column
value with LAST_INSERT_ID(expr).
The reason for the differences between LAST_INSERT_ID() and
mysql_insert_id() is that LAST_INSERT_ID() is made easy to use in
scripts while mysql_insert_id() tries to provide more exact
information about what happens to the AUTO_INCREMENT column.
PHP mysqli_insert_id()
Performing an INSERT or UPDATE statement using the LAST_INSERT_ID()
function will also modify the value returned by the mysqli_insert_id()
function.
Putting it all together:
$affected_rows = DB::getAffectedRows("
update users set status = 'processing'
where status = 'pending' and last_insert_id(user_id)
limit 1"
);
if ($affected_rows) {
$user_id = DB::getInsertId();
}
(FYI that DB class is here.)
This is the same method as Salman A's answer, but here's the code you actually need to do it.
First, edit your table so that it will automatically keep track of whenever a row is modified. Remove the last line if you only want to know when a row was initially inserted.
ALTER TABLE mytable
ADD lastmodified TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
Then, to find out the last updated row, you can use this code.
SELECT id FROM mytable ORDER BY lastmodified DESC LIMIT 1;
This code is all lifted from MySQL vs PostgreSQL: Adding a 'Last Modified Time' Column to a Table and MySQL Manual: Sorting Rows. I just assembled it.
Query :
$sqlQuery = "UPDATE
update_table
SET
set_name = 'value'
WHERE
where_name = 'name'
LIMIT 1;";
PHP function:
function updateAndGetId($sqlQuery)
{
mysql_query(str_replace("SET", "SET id = LAST_INSERT_ID(id),", $sqlQuery));
return mysql_insert_id();
}
It's work for me ;)
SET #uids := "";
UPDATE myf___ingtable
SET id = id
WHERE id < 5
AND ( SELECT #uids := CONCAT_WS(',', CAST(id AS CHAR CHARACTER SET utf8), #uids) );
SELECT #uids;
I had to CAST the id (dunno why)... or I cannot get the #uids content (it was a blob)
Btw many thanks for Pomyk answer!
Hey, I just needed such a trick - I solved it in a different way, maybe it'll work for you. Note this is not a scalable solution and will be very bad for large data sets.
Split your query into two parts -
first, select the ids of the rows you want to update and store them in a temporary table.
secondly, do the original update with the condition in the update statement changed to where id in temp_table.
And to ensure concurrency, you need to lock the table before this two steps and then release the lock at the end.
Again, this works for me, for a query which ends with limit 1, so I don't even use a temp table, but instead simply a variable to store the result of the first select.
I prefer this method since I know I will always update only one row, and the code is straightforward.
ID of the last updated row is the same ID that you use in the 'updateQuery' to found & update that row. So, just save(call) that ID on anyway you want.
last_insert_id() depends of the AUTO_INCREMENT, but the last updated ID not.
My solution is , first decide the "id" ( #uids ) with select command and after update this id with #uids .
SET #uids := (SELECT id FROM table WHERE some = 0 LIMIT 1);
UPDATE table SET col = 1 WHERE id = #uids;SELECT #uids;
it worked on my project.
Further more to the Above Accepted Answer
For those who were wondering about := & =
Significant difference between := and =, and that is that := works as a variable-assignment operator everywhere, while = only works that way in SET statements, and is a comparison operator everywhere else.
So SELECT #var = 1 + 1; will leave #var unchanged and return a boolean (1 or 0 depending on the current value of #var), while SELECT #var := 1 + 1; will change #var to 2, and return 2.
[Source]
If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.
If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.
Having set this, you can then use a query like:
SELECT id FROM table ORDER BY last_modified DESC LIMIT 1;
to get the most recently modified row.
No need for so long Mysql code. In PHP, query should look something like this:
$updateQuery = mysql_query("UPDATE table_name SET row='value' WHERE id='$id'") or die ('Error');
$lastUpdatedId = mysql_insert_id();