当MySQL数据库发生变化时,如何让我的网页上的元素自动更新?

时间:2016-05-18 17:52:30

标签: php mysql ajax

我创建了以下PHP代码,以生成MySQL数据库中所有注释的订阅源。

<?

$con = mysqli_connect("localhost","username","password","databasename");

if (!$con)
{
  die('Could not connect: ' . mysqli_connect_error());
}

$query = "SELECT * FROM tablename ORDER BY timestamp DESC LIMIT 0 , 1000";

$comments = mysqli_query($con, $query);

echo "<h1>Recent Posts</h1><br><br><hr>";

while($row = mysqli_fetch_array($comments, MYSQLI_ASSOC))
{
  $comment = $row['comment'];
  $timestamp = $row['timestamp'];
  $comment = htmlspecialchars($row['comment'],ENT_QUOTES);
  $score = $row['score'];
  $id = $row['id'];

  echo " <div class='card'>
      <p>$comment</p><br />
      <p>Post #$id</p>
      <p>Score: $score</p><br>
      <button onclick='myfunction($id,1)'>Upvote</button><button onclick='myfunction($id,-1)'>Downvote</button><br>
      <p style='color: grey'>$timestamp</p><hr>
    </div>
  ";
}

mysqli_close($con);

?>

它包含在包含以下js脚本的HTML文件中:

function myfunction(postid,vote){
$.ajax({
    type: "POST",
    url: 'addvote.php',
    data: {vote: vote, postid: postid, score: $("#postscore").val()},
    success: function(data){
        alert(data);
    }
});

}

文件addvote.php由以下代码给出:

<?php

  $con = mysqli_connect("localhost","username","password");

  if (!$con)
  {
    die('Could not connect: ' . mysqli_connect_error());
  }

    $vote = $_POST['vote'];
    $postid = $_POST['postid'];
    $userid = $_SERVER['REMOTE_ADDR'];

    $query2 = mysqli_query($con,"SELECT score FROM database.table WHERE id ='$postid'");
    $row = mysqli_fetch_array($query2, MYSQLI_ASSOC);
    $score = mysqli_real_escape_string($con,$row['score']);

    $newscore = $score + $vote;

  $query1 = mysqli_query($con,"SELECT * FROM database.table WHERE postid='$postid' AND ipaddress='$userid'");

  $numi = mysqli_num_rows($query1);

if($numi == 0){

  $query3 = "INSERT INTO `database`.`table` (`postid`, `ipaddress`, `vote`, `id`) VALUES ('$postid', '$userid', '$vote', NULL)";

  mysqli_query($con, $query3);

  $sql = "UPDATE `database`.`table` SET `score` = '$newscore' WHERE `mainfeed`.`id` = '$postid'";

  mysqli_query($con, $sql);

  echo "Thanks for voting!";

  }

  else {

  echo "You have already voted on post number ".$postid;

  }

  mysqli_close($con);

?>

这一切都可以正常工作,当它出现在投票和downvoting帖子时 - 它会改变MySQL数据库中的帖子得分而不刷新网页。但是,在重新加载页面之前,它不会更改网页上显示的分数。如何才能使分数的变化立即显示在网页上,而无需刷新?

提前致谢

1 个答案:

答案 0 :(得分:1)

我设法通过将php脚本中的变量data的值更改为posts分数的新值来解决此问题。我已经使用了

document.getElementById('score').innerHTML = data;

这样客户端值就会变为MySQL数据库中的值,而不必获取它。