2016-05-12 207 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。这是一个巨大的错误。