我目前正在转发名为“tbl_users”的表中名为“followers_count”的列的数据。该网站有多个用户,每个用户都有自己的页面。在这些页面上,用户可以单击关注按钮,然后使用 JSON 显示关注计数。到目前为止,代码有效,只是它仅显示/更新表中第一个“userID”的“followers_count”数据。我的问题是,如何更改代码,以便它知道每个用户的页面显示他们的 follower_count?
在changes.php中:
<?php
require_once 'class.channel.php';
$user_change = new USER();
$seqFollows = $user_change->runQuery("SELECT followers_count FROM tbl_users");
$seqFollows->execute();
$row = $seqFollows->fetch(PDO::FETCH_ASSOC);
$follow_count = $row['followers_count'];
header('Content-type: application/json');
$array = array('followers_count'=>$follow_count);
echo json_encode($array);
?>
在index.php?id=(用户页面模板)中:
<div>
Channel Adds: <div id="follow_count" style="display:inline;"></div>
</div>
<script type="text/javascript">
var timer;
timer = setInterval(function() {
$(document).ready(function(){
$.getJSON('changes.php', function(data) {
$('#follow_count').html(data.followers_count);
});
});
}, 1 * 1000);
</script>
同样在index.php?id=中,这是确定我当前正在查看的页面的代码:
$currentID = ( isset( $_GET['id']) && !empty( $_GET['id'] ) ) ? trim($_GET['id']) : '' ;
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$currentID));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
最佳答案
您需要告诉changes.php 用户ID 值是什么。您将需要修改您的index.php 文件以提供该值。一种选择是修改 AJAX 调用,类似于:
$(document).ready(function(){
$.getJSON('changes.php?id=<?php echo $_GET["id"]; ?>', function(data) {
$('#follow_count').html(data.followers_count);
});
});
然后你的changes.php文件需要像index.php一样获取$_GET['id']
的值。
关于PHP 和 JSON 按用户显示列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989237/