Programming, website development forum Get latest updates by RSS Follow TechnicalTalk on Twitter Follow TechnicalTalk on Facebook 
HomeSearchRecent PostsLoginRegisterContact Us

Username  
Password    
  Forgot your password?  

Pages: [1]   Go Down
 
  Email this topic  |  Print
0 Members and 1 Guest are viewing this topic.

Searching, Retrieving and updating the same row.

 
webmaster forum
Activity
0%
 
New Coder
Real name: Krishnan
Location: Kerala, South India
Gender: Male
Age: 17
Posts: 29
Topics: 10
September 22, 2011, 07:35:30 PM

Like when i have to increment a value in a certain row, I now do one SELECT statement, Then fetch_row and finally an UPDATE statement.

It looks like this
Quote
$res=mysql_query("SELECT field FROM table USE INDEX ( id ) WHERE id=$id");
$row=mysql_fetch_row($res);
$val=$row[0]+1;
mysql_query("UPDATE table SET field='$val' USE INDEX ( id )WHERE id=$id");


So i'm searching it twice, Once in the SELECT and once in the UPDATE. Is there a way i can make the UPDATE statement use the result from the SELECT statement?
 
webmaster forum
polas  Offline
Activity
33.33%
 
Code Guru
Gender: Male
Posts: 1399
Topics: 85
WWW
January 01, 2012, 01:10:11 PM

Just do

Code:
UPDATE table set field = field + 1 where id = $id

Mesham Type Oriented Parallel Programming Language, Free online technical support
 
webmaster forum
Activity
0%
 
New Coder
Real name: Krishnan
Location: Kerala, South India
Gender: Male
Age: 17
Posts: 29
Topics: 10
January 02, 2012, 05:19:50 AM

Thanks.

I had figured that out though Smiley

Now i have a new question.
Which is the most effective way to update a field based on multiple conditions?
I've seen a sort of switch statement with various cases but everyone was complaining about it being stupid.
It looked like the statement in here: http://www.java2s.com/Code/SQLServer/Select-Query/UseCASEintheUPDATEstatement.htm

I don't absolutely need it since it's a once a day query but i like to do things the right way Smiley
 
  Email this topic  |  Print
Pages: [1]   Go Up
 
Jump to:  



Powered by SMF 1.1.15 | SMF © 2011, Simple Machines


Google visited last this page February 05, 2012, 02:34:32 AM