【问题标题】:Get the individual answer from a sql count() into php从 sql count() 获取单个答案到 php
【发布时间】:2017-08-28 19:09:01
【问题描述】:

我有一个 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']; 显示单个结果,但事实证明,由于某种原因,这会返回“Array”。这是我的 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'];

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

【问题讨论】:

  • 你的意思是$row['Album'];而不是$row;['Album'];
  • y如果列名是albumtype你可以得到内容为$row['albumtype'];
  • wariostarx 请检查下面的答案并告诉我们是否有效?
  • 抱歉,我今天没时间处理它,明天再检查。是的,我提醒$row['Album'],将编辑帖子。

标签: php mysql sql count


【解决方案1】:

1.如果您只想要特定的albumType 10,您可以像这样直接更改您的查询:-

$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;
    }
}

【讨论】:

  • 感谢您的帮助。我使用了第一个代码,它似乎工作得很好。一旦数据库开始扩展,我会检查它,但我猜它会一直有效。我也会看看我将来是否需要第二个代码。
【解决方案2】:

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

foreach ($row as $srow) {
    if($srow['albumtype'] == 'Album'){
        print $srow['count'];
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    相关资源
    最近更新 更多