简体   繁体   English

计算并在PHP的不同列中显示多个mysql行值

[英]Count and display multiple mysql row values in different columns for PHP echo

I have using following mysql statement to count and retrieve multiple database rows in mysql database: 我已经使用以下mysql语句来计数和检索mysql数据库中的多个数据库行:

SELECT COUNT(*) FROM leavesrecords WHERE leavetype IN ('Casual','Annual','Medical') and empno = '202'  GROUP BY leavetype

But the output of this query only contain one column and the column name is COUNT(*) . 但是此查询的输出仅包含一列,列名称为COUNT(*) This query returns three counted values and I want those value to assign PHP variables. 该查询返回三个计数值,我希望这些值分配PHP变量。 following PHP code I used to get values: 以下我用来获取值的PHP代码:

include 'database.php';
$query = "SELECT COUNT(*) FROM leavesrecords WHERE leavetype IN ('Casual','Annual','Medical') and empno = '202'  GROUP BY leavetype; ";
$stmt = $con->prepare($query);
$stmt->execute();

$num = $stmt->rowCount();
if($num>0){
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        echo $row["leavesrecords"];
    } 
}
else{ echo "";}
?>

But this code throwing me an error without showing single value. 但是这段代码在没有显示单个值的情况下抛出了错误。 I want to assign those three mysql counts to three mysql variables. 我想将这三个mysql计数分配给三个mysql变量。 how can I do that? 我怎样才能做到这一点?

You should use an alias for thr column result 您应该为thr列结果使用别名

 SELECT COUNT(*) as my_count 
 FROM leavesrecords 
 WHERE leavetype IN ('Casual','Annual','Medical') and empno = '202'  GROUP BY leavetype

and refer to the column using the alias name for key 并使用别名的密钥引用该列

if($num>0){
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        // extract($row);
        echo $row["my_count"];
    } 
}

You should not refer to the rows contens using the tablename but a proper column name 您不应使用表名而是使用正确的列名来引用行内容

Consider using an IF or CASE statement in your query to return a single row: 考虑在查询中使用IFCASE语句返回单行:

 SELECT sum(if(leavetype='Casual',1,0)) AS `CasualCount`,
    sum(if(leavetype='Annual',1,0)) AS `AnnualCount`,
    sum(if(leavetype='Medical',1,0)) as `MedicalCount`
FROM leaverecords
WHERE leavetype IN ('Casual','Annual','Medical') and empno = '202';

Now you will have 1 row with three fields. 现在,您将有1行包含3个字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM