如何在while循环中获取结果

时间:2018-11-19 00:04:51

标签: php mysql loops

我有以下2张桌子。

my_plot <- ggplot(all_data, aes(x=Sepal.Length)) +
geom_density() +
geom_vline(xintercept = labels$label_position) 

text_position <- mean(ggplot_build(my_plot)$layout$panel_scales_y[[1]]$range$range)

my_plot + geom_text(data = labels, aes(x=label_position, y = text_position), label = 
labels$label_text, vjust=-0.5, size=4, angle = 90)

我想显示带有计数器的所有类别,例如:

| ID | Name        | Category |
|----|-------------|----------|
|  1 | Foo bar     | 3        |
|  2 | Bar foo     | 2        |
|  3 | Baz Foo     | 3        |
|  4 | Baz Foo2    | 1        |
|  5 | Baz Foo3    | 1        |
|  3 | Baz Foo     | 1        |

| ID | Category_name |
|----|---------------|
|  1 | Cat 111       | 
|  2 | Cat 222       | 
|  3 | Cat 3333      | 

我尝试通过以下方式进行操作,但不起作用:

Cat111 - 3
Cat222 - 2
Cat333 - 2

1 个答案:

答案 0 :(得分:2)

您没有共享表的名称,但是我假设第一个是Gallery,第二个是pics_cat

如果您的表不会很大,建议您使用单个联接查询来解决所有问题,从而简化脚本的逻辑。

$query = mysqli_query($conn, 'SELECT p.Category_name,COUNT(g.ID) AS cnt FROM `gallery` AS g LEFT JOIN `pics_cat` AS p ON p.ID = g.Category GROUP BY p.ID');

while($row = mysqli_fetch_assoc($query)) {
    echo $rowCat['Category_name'];
    echo $rowCat['cnt'];
}

如果您希望循环使用两个查询来执行此操作,那么从Category表开始然后移至图库会容易得多

$query = mysqli_query($conn, 'SELECT * FROM `pics_cat` ORDER BY ID');

while($row = mysqli_fetch_assoc($query)) {
    $query_count = mysqli_query('SELECT COUNT(ID) AS cnt FROM `gallery` WHERE Category = '.$row['ID'].'');
    $row_count = mysqli_fetch_assoc($query_count);
    echo $row['Category_name'];
    echo $row_count['cnt'];
}