Is it possible in MySQL+PHP to increase an INT value and return the new value within one query?
$sql = mysql_query("UPDATE table SET number=number+1 WHERE id='uniqid'");
$updated_number = ???
Or I need to post another query?
SELECT number FROM table WHERE id='uniqid'
For the single-table syntax, the UPDATE statement updates columns of existing rows in the named table with new values. The SET clause indicates which columns to modify and the values they should be given. Each value can be given as an expression, or the keyword DEFAULT to set a column explicitly to its default value.
MySQL UPDATE multiple columnsMySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.
Simple answer - no, it's not possible.
Longer answer, yes, if you use a stored procedure that increments the value for the specified ID, retrieves the new value and returns it.
I've just tested this under MySQL 5.1.59:
CREATE PROCEDURE increment (IN uniqid VARCHAR(255))
BEGIN
UPDATE `table` SET number = number + 1 WHERE id = uniqid;
SELECT number FROM `table` WHERE id = uniqid;
END
Usage:
CALL increment(uniqid)
If multiple simultaneous accesses are possible you may wish to LOCK
the table first to ensure the operation's atomicity - MySQL apparently doesn't allow stored procedures to lock tables themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With