mysql 值减1_在MySQL中将行值增加和减少1

bd96500e110b49cbb3cd949968f18be7.png

Hi I have a MySQL database table "points" the user can click a button and a point should be removed from their account, the button they pressed has an ID of another user, therefore their account must increase by one.

I have it working in jQuery and checked the varibles/posts in Firebug, and it does send the correct data, such as:

userid= 1

posterid = 4

I think the problem is with my PHP page:

include ('../functions.php');

$userid=mysql_real_escape_string($_POST['user_id']);

$posterid=mysql_real_escape_string($_POST['poster_id']);

if (loggedin())

{

include ('../connection.php');

$query1 = "UPDATE `points` SET `points` = `points` - 1 WHERE `userID` = '$userid'";

$result1=mysql_query($query1);

$query2 = "UPDATE `points` SET `points` = `points` + 1 WHERE `userID` = '$posterid'";

$result2=mysql_query($query2);

if ($result1 && result2)

{

echo "Successful";

return 1;

}

else

{

echo mysql_error();

return 0;

}

}

?>

Any ideas? Thanks :)

解决方案

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值