2016-05-12 254 views
-1

你好,我想使使用PHP和MySQL相似的系統上的類似按鈕點擊我也是在數據庫中插入數據時,但插入錯誤的數據庫值,但像價值爲0沒有增量和未定義的錯誤發生。任何人都可以幫助我解決這個問題顯示錯誤消息時

There is my Like button code : 

<?php 
    //// work with like box 
     $get_likes = mysqli_query($con,"SELECT * FROM `likes`"); 
     if (mysqli_num_rows($get_likes)===1) { 

      $get = mysqli_fetch_assoc($get_likes); 
      // $uid = $get['uid']; 
      $total_likes = $get['total_likes']; 
      //echo $uid; 
      $total_likes = $total_likes + 1; 
      //echo $total_likes++; 
     } 

    if (isset($_POST['likebutton_'])) { 
     $like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con)); 

    //$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn)); 
    header("Location:home.php"); 

    } 

    else 
    { 
     echo "Error"; 
    } 
    ?> 
    this code work fine without insert Data 
    There is My liked with Data Insertd Code 
    <?php 
    ////work with like box 
     $get_likes = mysqli_query($con,"SELECT * FROM `likes`"); 
     if (mysqli_num_rows($get_likes)===1) { 

      $get = mysqli_fetch_assoc($get_likes); 
      // $uid = $get['uid']; 
      $total_likes = $get['total_likes']; 
      //echo $uid; 
      $total_likes = $total_likes + 1; 
      //echo $total_likes++; 
     } 

    if (isset($_POST['likebutton_'])) { 
     $like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con)); 

    $insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn)); 
    header("Location:home.php"); 

    } 

    else 
    { 
     echo "Error"; 
    } 
    ?> 
    this is output i want to display my font-end page <?php echo $total_likes ;?> but it occur error 

    The error is Undefined Variable 
I also try $total_likes=""; 
as global but still not work 
+0

您可以添加代碼的形式,數據庫和你想顯示對結果的前端頁面? – Richard

+0

你不需要'''''只需要'mysql'就可以更新當前行+1。你可以使用這段代碼進行SQL注入。你也不應該傳遞一些ID,所以你不更新每個記錄? – chris85

+0

你遇到了我的猜測的問題是,'mysqli_num_rows($ get_likes)'不等於'1'。你只有在計數爲1 – chris85

回答

0

您的代碼患有競爭條件。你應該做的是這樣的模式:

INSERT INTO likes (uid, total_likes) VALUES (?, 1) 
    ON DUPLICATE KEY SET total_likes=total_likes+1 

如果您使用bind_param設置佔位符的價值,你的UID。

請注意,在您的一個查詢中,您將總計數設置爲,所有都喜歡+1。這是一個巨大的錯誤。