2012-07-22 43 views
2

我試圖從MySQL數據庫中檢索值並將其轉換爲int,並向其中添加3,並試圖將更新int存儲到數據庫中。我沒有收到任何錯誤或任何內容。我從數據庫檢索到的初始值是5並比即時嘗試添加3,並更新數據庫。現在更新的值應該是8但它不是,而是它只是3.我不知道我在做什麼錯誤,所以請幫助我。在php中將從MySQL查詢獲取的字符串/ val轉換爲int?

從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); 
     } 

謝謝!!

回答

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中完成。

+1

謝謝你的response.it工作:) – Viking 2012-07-22 01:20:47

+0

這總是很好聽! – 2012-07-22 01:24:58