【问题标题】:How to count the number of row with select count(*)如何使用 select count(*) 计算行数
【发布时间】:2013-11-04 21:47:53
【问题描述】:

我尝试使用带有多个参数的 select count(*) 获取行数并将其编码为 JSON 格式,但我得到了这个:

{"notification":[{"count(*)":0}],"message":[{"count(*)":0}]}

而不是例外:

{"notification":0,"message":0}

这里有页面的代码:

session_start();
require_once __DIR__ . '/mysql/Db.class.php';
$bdd = new Db();
$t = array();

$query = $bdd->query("SELECT count(*) FROM notification WHERE id_proprio = :id_proprio AND readed = :readed", array("id_proprio"=> $_SESSION['userid'],"readed"=>"0"));
$query_2 = $bdd->query("SELECT count(*) FROM discussion WHERE id_1 = :uid AND readed = :readed AND notifPour = :uid2 OR id_2 = :uid3 AND readed = :readed2 AND notifPour = :uid4", array(
  "uid"=> $_SESSION['userid'],
  "readed"=>"0",
  "uid2"=> $_SESSION['userid'],
  "uid3"=> $_SESSION['userid'],
  "readed2"=>"0",
  "uid4"=> $_SESSION['userid']
));


$t["notification"] = $query;
$t["message"] = $query_2;

echo json_encode($t);

包括Db类的一部分:

public function query($query,$params = null,$fetchmode = PDO::FETCH_ASSOC)
{
    $query = trim($query);

    $this->Init($query,$params); // INIT IS THE CONNECTION TO DB

    if (stripos($query, 'select') === 0) {
        return $this->sQuery->fetchAll($fetchmode);
    }
    elseif (stripos($query, 'insert') === 0 ||  stripos($query, 'update') === 0 || stripos($query, 'delete') === 0) {
    return $this->sQuery->rowCount(); 
    } else {
        return NULL;
    }
}

我怎样才能得到这样的例外结果格式:

{"notification":0,"message":0}

谢谢。

【问题讨论】:

    标签: php mysql json pdo


    【解决方案1】:

    修改您的 SQL 查询以开始:

    SELECT count(*) AS cnt FROM
    

    然后像这样从查询中获取值:

    $t["notification"] = $query[0]["cnt"];
    $t["message"] = $query2[0]["cnt"];
    

    【讨论】:

      【解决方案2】:

      您的 MySQL API 返回一个包含所有行的数组,每一行都是一个关联数组,其键是 SELECT 子句中的标签。您需要从数组中提取值:

       $t["notification"] = $query[0]['count(*)'];
       $t["message"] = $query_2[0]['count(*)'];
      

      【讨论】:

        猜你喜欢
        • 2012-10-08
        • 2015-04-18
        • 2018-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-05
        • 2023-01-30
        • 1970-01-01
        相关资源
        最近更新 更多