Updating a row... +=1

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
figaro11
Forum Commoner
Posts: 64
Joined: Mon Sep 17, 2007 11:49 pm

Updating a row... +=1

Post by figaro11 »

How can I update a tables rows field to equal to the current value plus 1? In other words Something like this:

Code: Select all

UPDATE registry SET value += 1 WHERE class = 'Hit Counter' LIMIT 1;
It's hard for me to explain, and I'm not very SQL savvy. So hopefully you get the idea.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Close ;)

Code: Select all

UPDATE `registry` SET `value` = `value` + 1 WHERE `class` = 'Hit Counter' LIMIT 1; 
User avatar
figaro11
Forum Commoner
Posts: 64
Joined: Mon Sep 17, 2007 11:49 pm

Post by figaro11 »

Jcart wrote:Close ;)

Code: Select all

UPDATE `registry` SET `value` = `value` + 1 WHERE `class` = 'Hit Counter' LIMIT 1; 
Sweet! But why quote the table/field names?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

To protect against the use of keywords as database, table and field names. Although one should simply not use keywords or potential future keywords.
User avatar
figaro11
Forum Commoner
Posts: 64
Joined: Mon Sep 17, 2007 11:49 pm

Post by figaro11 »

feyd wrote:To protect against the use of keywords as database, table and field names. Although one should simply not use keywords or potential future keywords.
Oooooooh. I see.

But I get this error when I do use qoutes:
Warning: Wrong parameter count for mysql_query() in /home/content/html/lib/php/hit-counter.php on line 7
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Adding backticks wouldn't create such an error.
User avatar
figaro11
Forum Commoner
Posts: 64
Joined: Mon Sep 17, 2007 11:49 pm

Post by figaro11 »

feyd wrote:Adding backticks wouldn't create such an error.
What are backticks?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

The type of quotes Jcart used above.

Note the difference: ` versus '
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

These days I go further than just using backticks, I use the fully qualified table column pair. Eg

Code: Select all

UPDATE `registry` SET `registry`.`value` = `registry`.`value` + 1 WHERE `registry`.`class` = 'Hit Counter' LIMIT 1;
It makes no difference in a simple statement like that one, but in a select with 10 tables joined together I find it really improves readability.
Post Reply