Jump to content

Mysql SELECT and UPDATE in same command


loki951510
Go to solution Solved by Ch0cu3r,

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
Edited by loki951510
Link to comment
Share on other sites

  • Solution

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";
Link to comment
Share on other sites

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.

Edited by mac_gyver
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.