Skip to Content »

FlashApe » Cool MySQL increment/decrement value tip

 Cool MySQL increment/decrement value tip

  • September 28th, 2008
  • 7:34 pm

I needed to adjust a value in a column in a database table by 1, for all rows. I found out you can do it easily by doing this:

PHP:
  1. $sql = "UPDATE images SET displayIndex=displayIndex +1 WHERE gallery_id=1";

Turning that into a function we can specify if we want to increment or decrement the value pretty easily. You can also provide a starting point for the adjustment (so if you delete the item with displayIndex=15, you only want to decrement the displayIndexes greater than 15 by 1) and specify a different value for the WHERE clause:

PHP:
  1. public function updateDisplayIndexes($galleryID, $startIndex, $add = true){
  2.    
  3.     $operator = ($add) ? '+' : '-';
  4.  
  5.     $sql = "UPDATE images SET displayIndex=displayIndex".$operator."1 WHERE gallery_id=$galleryID AND displayIndex> $startIndex"
  6.     $result = mysql_query ($sql);
  7. }

There's a lot more you can do with it but it's been a pretty good starting point.

Want your say?

* Required fields. Your e-mail address will not be published on this site


You can use the following XHTML tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>