如何使我的网页上的元素在它';s MySQL数据库更改


How can I make elements on my webpage automatically update when it's MySQL database changes?

我创建了以下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);
?>

它包含在一个HTML文件中,该文件包含以下js脚本:

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);
?>

当它出现向上投票和向下投票的帖子时,这一切都很好——它可以在不刷新网页的情况下更改MySQL数据库中的帖子分数。但是,在重新加载页面之前,它不会更改网页上显示的分数。我如何使分数的更改立即显示在网页上,而无需刷新?

提前感谢

我通过将php脚本中变量data的值更改为posts score的新值来解决这个问题。然后我用了

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

这样客户端的值就可以更改为MySQL数据库中的值,而不必提取它。