Increasing a db value by 1

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nite4000
Forum Contributor
Posts: 209
Joined: Sun Apr 12, 2009 11:31 am

Increasing a db value by 1

Post by nite4000 »

Hey,

I am working on part of my script and I need to increase a db field by value of 1 it starts as 0(zero) i then need it to go to 1 then 2 and so on.

I also need to check the db field to equal another db field like this

First db field is the field that has the already given value
second db field is the field that increases

if

Code: Select all

 $second['dbvalue'] == $first['dbvalue']
stop increasing and add balance to other
else continue

I hope this makes since

Don
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Increasing a db value by 1

Post by JakeJ »

First of all, it's generally bad practice to change the value within the array (though there are sometimes reasons).

$first = $first['dbvalue'];
$second = $second['dbvalue'];

To increment a value use: $second ++; (that's the same as $second = $second +1;).

To compare two statements, use a proper IF statement as follows:

Code: Select all

IF ($first==$second) {
 //do something
}
Else {
 //do something else
}
The else is not necessary, just included for completeness.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Increasing a db value by 1

Post by s.dot »

Pretty simple... here is how I would do it in psuedo-code

Code: Select all

$result = mysql_query("SELECT `field1`, `field2` FROM `table`");
$array = mysql_fetch_assoc($result);

if ($array['field2'] == $array['field1'])
{
    $added = $array['field2'] + $array['field1'];
    echo 'The fields are equal, so I added them together and got ' . $added;
} else
{
    mysql_query("UPDATE `table` SET `field1`=`field`+1");
    echo 'The fields are not equal, so I increased field 1 by 1";
}
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply