我试图返回一个名为“followers\u count”的列的值。在我的网站上我有几个用户,每个都有自己的计数。更新是有效的,当您单击follow时,它会在数据库中更新,但我想使用JSON来显示更改,而不需要刷新页面。到目前为止,代码仍然有效,但它只返回最后一个注册用户的followers_count值。有人知道为什么吗?
在changes.php中:
<?php
require_once 'class.channel.php';
$user_change = new USER();
$stmt = $user_change->runQuery("SELECT followers_count FROM tbl_users");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$currFollows = $row['followers_count'];
$seqFollows = $user_change->runQuery( "SELECT currval('followers_count')" );
if ($seqFollows == $currFollows){
exit(0);
}
$query = $user_change->runQuery($seqFollows);
while($row = $stmt->fetch($query))
{
$follows = $row['followers_count'];
}
header('Content-type: application/json');
$array = array('followers_count'=>$follows);
echo json_encode($array);
?>
在index.php中:
<div>
Channel Adds: <div id="follow_count"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('changes.php', function(data) {
$('#follow_count').html(data.followers_count);
});
});
</script>
最佳答案
在循环查看数据库结果时,每次都要替换$follows的值,因此只存储最后一个值。
要将每个计数添加到数组中,需要更改以下内容:
while($row = $stmt->fetch($query)) {
$follows = $row['followers_count'];
}
对此:
while($row = $stmt->fetch($query)) {
$follows[] = $row['followers_count'];
}
更新:
您的查询有问题:
$seqFollows = $user_change->runQuery( "SELECT currval('followers_count')" );
[...]
$query = $user_change->runQuery($seqFollows);
您正在尝试运行
$seqFollows
这是一个值而不是一个查询,这样就不会得到您要查找的结果。你说你正在做
$query = $user_change->runQuery($seqFollows);
来获得$seqFollows
的值,但是你已经拥有了它。因此,我建议您尝试将change.php更改为以下内容,以将$seqFollows
传递回followers_count
<?php
require_once 'class.channel.php';
$user_change = new USER();
$stmt = $user_change->runQuery("SELECT followers_count FROM tbl_users");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$currFollows = $row['followers_count'];
$seqFollows = $user_change->runQuery( "SELECT currval('followers_count')" );
$seqFollows->execute();
$row = $seqFollows->fetch(PDO::FETCH_ROW);
$follow_count = $row[0];
if ($follow_count == $currFollows){
exit(0);
}
header('Content-type: application/json');
$array = array('followers_count'=>$follow_count);
echo json_encode($array);
?>