从sql count()获取个人答案到php

问题描述 投票:3回答:2

我有一个sql数据库,我请求下面的代码; SELECT albumtype, COUNT(*) FROM albumdata GROUP BY albumtype

phpMyAdmin中的响应如下表所示

  • 专辑类型计数(*)
  • 专辑| 4
  • EP | 1
  • 单身| 1

然后我在我的php文件中有以下代码,它将返回完整的计数(6)。

$stmt = $con->prepare('SELECT albumtype, COUNT(*) FROM albumdata GROUP BY albumtype');
$stmt->execute() or die("Invalid query");
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$row_cnt = mysqli_num_rows($result);

我在另一个页面上使用了这段代码,但现在我想选择“count()”表的特定部分。

我试图用$row_cnt = $row['Album'];显示一个结果,但事实证明,由于某种原因,它返回“数组”。这是我的php调用:

$stmt = $con->prepare('SELECT albumtype, COUNT(*) FROM albumdata GROUP BY albumtype');
$stmt->execute() or die("Invalid query");
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$row_cnt = $row['Album'];

我如何获取单行,例如数据库可以找到Album的数量(4次)并将其放入php变量中?我试着在这里搜索,但没有进一步。

php mysql sql count
2个回答
2
投票

1.如果您只想要特定的albumType十,您可以直接更改您的查询,如下所示: -

$stmt = $con->prepare("SELECT albumtype, COUNT(*) as counts FROM albumdata WHERE albumtype = 'Album'");
$stmt->execute() or die("Invalid query");
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$album_cnt = $row['counts'];
echo $album_cnt;

但是如果你想要所有的话,你需要像下面这样做: -

$stmt = $con->prepare('SELECT albumtype, COUNT(*) as counts FROM albumdata GROUP BY albumtype');
$stmt->execute() or die("Invalid query");
$result = $stmt->get_result();
$row_cnt = array();

while($row = $result->fetch_assoc()){
  $row_cnt[$row['albumtype']] = $row['counts'];
}

echo "<pre/>";print_r($row_cnt); 
// you have all data in array so you can use it now like below

foreach($row_cnt as $key=>$value){
  echo "Album type ".$key." has ".$value." counts"."<br/>";
}

//form this all data if you want to compare specific albumType then do like below:-

foreach ($row_cnt as $key=>$value) {
    if($key == 'Album'){
        echo $value;
    }
}

1
投票

循环遍历行,直到匹配要显示的类型:

foreach ($row as $srow) {
    if($srow['albumtype'] == 'Album'){
        print $srow['count'];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.