JSON从PDO查询返回错误的值

时间:2017-08-31 01:50:33

标签: php mysql json pdo

我试图返回名为" followers_count"的列的值。在我的网站上,我有几个用户,每个用户都有自己的计数。更新工作,因为当您单击跟随它时,数据库中的更新,但我想使用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>

1 个答案:

答案 0 :(得分:2)

当你遍历数据库结果时,每次都会替换$的值,所以你只能存储最后一个值。

要将每个计数添加到数组,您需要更改它:

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