Increase and decrease row value by 1 in MySQL

Here is the example query, tested by me and it is working 100%

$query="UPDATE table_name SET `hit_count`=(`hit_count`+1) WHERE `id` = '1'";

Two queries to increase/decrease field value are not necessary:

mysql_query("UPDATE table SET field = field + 1 WHERE id = $number");

is a perfectly valid query as you can see next:

mysql> describe points;
+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| uid    | int(11) | NO   | PRI | NULL    |       |
| points | int(11) | YES  |     | 0       |       |
+--------+---------+------+-----+---------+-------+
2 rows in set (0.05 sec)

mysql> insert into points VALUES (1,0),(2,0);
Query OK, 2 rows affected (0.14 sec)

mysql> select * from points;
+-----+--------+
| uid | points |
+-----+--------+
|   1 |      0 |
|   2 |      0 |
+-----+--------+
2 rows in set (0.05 sec)

mysql> update points set points = points+1 where uid = 1;
Query OK, 1 row affected (0.27 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from points;
+-----+--------+
| uid | points |
+-----+--------+
|   1 |      1 |
|   2 |      0 |
+-----+--------+
2 rows in set (0.00 sec)

Having that tested, are you sure you get into your if (loggedin()) clause?

I have to agree with KM, would be nice to see output of echo $query1; or echo $query2;


update table_name set  col_name=col_name+1   where sqId = 12

But if your col_name by default value is null or empty it never works, so make sure that col_name default value is 0 or any integer value.

Tags:

Mysql

Sql

Php