Jump to content
New Reality: Ads For Members ×

Mysql SELECT and UPDATE in same command


loki951510

Recommended Posts

i have this sql stament and i cant get it to work

            $sql2 = "SELECT pad_count FROM user WHERE pad_id = 1";
            $sql = "UPDATE user ". "SET pad_count = ($sql2 + $pad_count) ". "WHERE pad_id = $pad_id" ;

this is the error im getting from it can some one help me plz

Could not update data: You can't specify target table 'user' for update in FROM clause
Link to comment
https://forums.phpfreaks.com/topic/298673-mysql-select-and-update-in-same-command/
Share on other sites

What are you trying to do? Increment pad_count by a certain amount? There is no need for the select query to get the current pad_count. You can reference the pad_count column in your update query and do simple arithmetic

$pad_id = 1;
$add_pad_count = 2;  // add 2 to the current pad_count column
$sql = "UPDATE user SET pad_count = (pad_count + $add_pad_count) WHERE pad_id = $pad_id";

even if you use a SELECT query to get the initial value, only use this for display purposes. any updating of the value should be done in a single query, so that you don't loose data when there are multiple concurrent instances of your code running, each trying to modify the value.

 

or better yet, don't maintain a count/accumulator in a table column. instead, insert a separate row into a database table for each transaction that modifies a value, then sum up the values from the rows to get the current total. this will give you an audit trail so that you can detect things like double-page requests, programming errors, or if someone manages to find a security hole in your code and submits an arbitrary data value that modifies the count/accumulator by more than you want.

Archived

This topic is now archived and is closed to further replies.



×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.