我试图从MySQL数据库中检索值并将其转换为int而不是向它添加3并尝试将更新int存储到database.Im没有得到任何错误或任何东西。我从数据库检索的初始值是5,而不是我试图添加3,而不是更新数据库。现在更新的值应该是8,但它不是它只是3.我不知道我做错了什么,所以请帮帮我。
我在index.php中的php代码如下:
else if ($tag == 'addQuestion'){
$username = mysql_real_escape_string($_POST['username']);
$question = mysql_real_escape_string($_POST['question']);
$tag1 = mysql_real_escape_string($_POST['tag1']);
$tag2 = mysql_real_escape_string($_POST['tag2']);
$tag3 = mysql_real_escape_string($_POST['tag3']);
$time = $_POST['time'];
$addQu = $db->addQuestion($username, $question, $tag1, $tag2, $tag3,$time);
if($addQu){
$q_id = $addQu["id"];
$addQTA = $db->addQTA($username,$q_id,$question,$tag1,$tag2,$tag3);
if($addQTA){
$getKP= $db->getKP($username);
if($getKP){
//Having trouble at this part
$kp = (int)$getKP['karma_points'];
$ask_question_points = $kp + 3;
$updateKP= $db->updateKP($username,$ask_question_points);
if($updateKP){
$response["error"] =1;
$response["msg"] = "updateKP in AddQuestion Succesfull";
echo json_encode($response);
}
else{
$response["error"] =1;
$response["error_msg"] = "Error updateKP in AddQuestion";
echo json_encode($response);
}
}
else{
$response["error"] =1;
$response["error_msg"] = "Error inserting getKP in AddQuestion";
echo json_encode($response);
}
}
else{
$response["error"] =1;
$response["error_msg"] = "Error inserting QTA";
echo json_encode($response);
}
}else{
$response["error"] =1;
$response["error_msg"] = "Error inserting question";
echo json_encode($response);
}
}
以下是处理更新查询的DB_functions.php函数的代码:
public function updateKP($username,$karma_points){
$result = mysql_query("UPDATE users SET karma_points = '$karma_points' WHERE username = '$username'") or die(mysql_error());
return($result);
}
谢谢!!
答案 0 :(得分:2)
你应该省去头痛并在一个查询中做到这一点:
$result = mysql_query("UPDATE users SET karma_points = karma_points + $karma_points WHERE username = '$username'") or die(mysql_error());
这会自动增加用户karma_points
的列$username
,其值为$karma_points
。而不是在PHP中进行数学运算并将其发送回MySQL,只需在MySQL中进行。