SQL计数未在PHP表上显示结果?
我的SQL表:
| user | bln | tipe |
|----- |-----| -----|
| A | 1 | 2 |
| A | 1 | 2 |
| B | 1 | 2 |
| A | 1 | 1 |
| C | 1 | 1 |
| D | 1 | 1 |
使用计数,在PHP中,我想列出这样的表:
| user |COUNT(tipe)|
|----- |-----------|
| A | 2 |
| B | 1 |
| C | 0 |
| D | 0 |
$sql = mysqli_query($link, "SELECT user, COUNT(tipe) FROM keg where bln=1 and tipe=2 GROUP BY user order by id asc;");
if(mysqli_num_rows($sql) == 0){
echo '<tr><td colspan="8">Tidak ada data.</td></tr>';
}else{
$no = 1;
while($row = mysqli_fetch_assoc($sql)){
echo '
<tr>
<td>'.$no.'</td>
<td>'.$row['user'].'</td>
<td>'.$row['tipe'].'</td>
</tr>
';
$no++;
}
}
?>
但是表输出是这样的:
| user |COUNT(tipe)|
|----- |-----------|
| A | |
| B | |
我的问题是$ row = mysqli_fetch_assoc($ sql)
吗?
我在SQL窗口中尝试了SQL,并且正常显示输出,但它不在PHP中。
My SQL table:
| user | bln | tipe |
|----- |-----| -----|
| A | 1 | 2 |
| A | 1 | 2 |
| B | 1 | 2 |
| A | 1 | 1 |
| C | 1 | 1 |
| D | 1 | 1 |
Using COUNT, in PHP I want to list the table like this:
| user |COUNT(tipe)|
|----- |-----------|
| A | 2 |
| B | 1 |
| C | 0 |
| D | 0 |
$sql = mysqli_query($link, "SELECT user, COUNT(tipe) FROM keg where bln=1 and tipe=2 GROUP BY user order by id asc;");
if(mysqli_num_rows($sql) == 0){
echo '<tr><td colspan="8">Tidak ada data.</td></tr>';
}else{
$no = 1;
while($row = mysqli_fetch_assoc($sql)){
echo '
<tr>
<td>'.$no.'</td>
<td>'.$row['user'].'</td>
<td>'.$row['tipe'].'</td>
</tr>
';
$no++;
}
}
?>
But the table output is like this:
| user |COUNT(tipe)|
|----- |-----------|
| A | |
| B | |
Is my problem in $row = mysqli_fetch_assoc($sql)
?
I tried the SQL in an SQL windows and it's showing the output normally, but it doesn't in PHP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有两个问题。首先,在PHP侧,您正在尝试在结果集中访问列
Tipe
,但是没有这样的列 - 它称为Count(Tipe)(Tipe)
。这可以通过使用别名来解决。其次,您的 子句删除所有没有
bln = 1的行,而tipe = 2
,因此您没有为用户C和D获得任何结果。一种解决方案是不使用
在其中
子句,而是将条件移至case
count> Count
函数的表达式以进行评估:There are two issues here. First, from the PHP side, you're trying to access the column
tipe
in the result set, but there is not such column - it's calledCOUNT(tipe)
. This can be solved by using an alias.Second, your
where
clause removes all the rows that don't havebln=1 and tipe=2
, so you aren't getting any results for users C and D.One solution would be to not use a
where
clause, but move the condition to acase
expression for thecount
function to evaluate: