doushaju4901 2017-08-28 19:09
浏览 56
已采纳

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

I have a sql database where I request the following bit of code;
SELECT albumtype, COUNT(*) FROM albumdata GROUP BY albumtype

The response in phpMyAdmin is the following table

  • albumtype | COUNT(*)
  • Album | 4
  • EP | 1
  • Single | 1

Then I have in my php file the following code that will return the complete count (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);

I used this code on another page, but now I want to select a specific part of the "count()" table.

I tried to display a single result with $row_cnt = $row['Album'];, but as it turns out, this returns "Array" for some reason. Here is my php call:

$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'];

How can I grab a single row, for example the number of how much the database could find Album (4 times) and put it in a php variable? I tried searching it on here, but didn't get any further.

  • 写回答

2条回答 默认 最新

  • doujugu1722 2017-08-28 19:15
    关注

    1.If you want only specific albumType ten you can directly change your query like this:-

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

    But if you want all then,you need to do it like below:-

    $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条)

报告相同问题?

悬赏问题

  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机