我想在mysql表中将值增加1但在提交后我发现它已经变为11而不是2,这是我的查询:
UPDATE likes_ SET likes = likes + 1 WHERE post_id = '$pid2'
已修改(评论部分的代码)
<?php
$pid2 = $_POST['like'];
if (isset($_POST['like'])) {
$q3 = mysql_query("SELECT likes FROM likes_ WHERE post_id = '$pid';");
$lk = mysql_num_rows($q3);
if ($lk == 0) {
mysql_query("INSERT INTO likes_ (id, likes, uid, post_id) VALUES (NULL, 1, '$uid', '$pid2');");
} else {
mysql_query("UPDATE likes_ SET likes = 'likes' + 1 WHERE post_id = '$pid2'");
}
}
答案 0 :(得分:1)
从您刚插入的代码中,您不能在字段名称周围使用'
。
做到:
mysql_query("UPDATE likes_ SET `likes` = `likes` + 1 WHERE post_id = '$pid2'");
我有一个有效的例子,请查看。
CREATE TABLE likes_ (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
likes INT(11) NOT NULL
);
INSERT INTO likes_ (id, likes) VALUES (NULL, 1);
UPDATE `likes_` SET `likes` = (`likes` + 1);
SELECT * FROM `likes_`
喜欢的结果将是2。
答案 1 :(得分:0)
我发现问题,插入查询中的var $ pid必须是$ pid2,非常感谢朋友
答案 2 :(得分:-1)
如果你输入强制转换为int,那么值可以像int一样计算。如果没有字符串值将像11那样组合。
UPDATE likes_ SET likes = CAST(likes AS int) + 1 WHERE post_id = '$pid2'
我认为这段代码也有用。单引号&#39;喜欢&#39;可能会更改为字符串值。因此它组合11而不是2
mysql_query("UPDATE likes_ SET likes = likes + 1 WHERE post_id = '$pid2'");
答案 3 :(得分:-1)
您可以尝试使用以下代码解决问题。
UPDATE likes_ SET `likes` = `likes` + 1 WHERE post_id = '$pid2'"
还要确保likes
个字段具有int数据类型。
答案 4 :(得分:-1)
您可以尝试:
$pid2 = $_POST['like'];
if (isset($_POST['like'])) {
$q3 = mysql_query("SELECT likes FROM likes_ WHERE post_id = '$pid';");
$lk = mysql_num_rows($q3);
$lkp = $lk['likes'] + 1;
if ($lk == 0) {
mysql_query("INSERT INTO likes_ (id, likes, uid, post_id) VALUES (NULL, 1, '$uid', '$pid2');");
} else {
mysql_query("UPDATE likes_ SET likes = ".$lkp." WHERE post_id = '$pid2'");
}
}