[英]Get the individual answer from a sql count() into php
我有一個sql數據庫,我請求下面的代碼;
SELECT albumtype, COUNT(*) FROM albumdata GROUP BY albumtype
phpMyAdmin中的響應如下表所示
然后我在我的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'];
顯示單個結果$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變量中? 我試着在這里搜索,但沒有進一步。
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;
}
}
循環遍歷行,直到匹配要顯示的類型:
foreach ($row as $srow) {
if($srow['albumtype'] == 'Album'){
print $srow['count'];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.