PHP 循环,单独的结果取决于 group_id

标签 php mysql

我有一个 PHP 循环遍历我的媒体表,在表中它们是这些字段: id(唯一的id_,post_id(每个帖子的随机id),user_id,file_format,group_id

如果上传一组多张图片,它们有一个唯一的post_id,并且有相同的group_id,以区分其他组的照片。但是我不知道如何使用 if 语句来分隔循环内的这些组来分解 div 行。 这是我的代码:

<?php
		$sql = "SELECT * FROM media WHERE user_id = '".$_SESSION['user']."'";
		$result = $conn->query($sql);
		?>
		
		<?php while($row = mysqli_fetch_array($result)):?>
			<?php $group_id = $row['group_id'] ?>
		<?php if($row['group_id'] == $group_id):?>
			<div class="card-group" style="color:black;">
			  <div class="card">
			    <img class="card-img-top" src="uploads/<?=$row['post_id']?>.<?=$row['file_format']?>" alt="Card image cap">
			    <div class="card-body">
			      <h4 class="card-title">Card title</h4>
			      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
			      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
			    </div>
			  </div>
			</div>
		<?php endif;?>
		<?php endwhile;?>

最佳答案

我假设你的表media是这样的:

+---------+-------------+-----------+-----------+---------+
|unique_id| post_id     | user_id   |file_format|group_id |
+---------+-------------+-----------+-----------+---------+
|1        |56           | johndoe66 |.jpg       |Home     |
+---------+-------------+-----------+-----------+---------+
|2        |57           | johndoe66 |.png       |School   |  
+---------------------------------------------------------+

因此,首先获取SELECT DISTINCT group_id FROM media WHERE user_id = $_SESSION['user_id']

$conn = new mysqli("server","user","pass","your_database_name");
//will use the Object Oriented way, i'm used to it
$sql = "SELECT DISTINCT group_id FROM media WHERE user_id = $_SESSION['user_id']`";

$groups_result = $conn->query($sql);
//create a group array and format it as you like
$user_groups = array();
while($row = $groups_result->fetch_array()){
   $user_groups[] = $row['group_id`];
}

这将首先获取该用户的所有不同组并将它们存储在 $user_groups 中。然后:

Foreach $user_groups:

您现在想要获取每个组的帖子:

for($i = 0;$i < count($user_groups);$i++){
  $sql = "SELECT * FROM media WHERE user_id = '".$_SESSION['user_id']."' AND group_id = '".$user_groups[$i]."'"
  //create a group div with maybe the <div id='$user_groups[$i]'>
   while($row = $mysqli_fetch_array($conn->query($sql)){
      //create a picture collage of all the posts in the current $i group
   }
  //close the group </div>
} 

编辑有帮助吗?

关于PHP 循环,单独的结果取决于 group_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46521875/

相关文章:

php - CSS hover 对 mysql fetch 的单个结果的影响

php - 拉拉维尔 : BadMethodCallException Method [show] does not exist

javascript - 使用 highchart 来自 MySQL 的实时数据

mysql - 在 MYSQL 中返回总分最高的学生姓名

php - 为什么 Symfony 5.1 不能识别 "routes.php"文件上配置的路由?

PHP PDO::MySQL 和 JQuery 和 Ajax

mysql - 如何在 TeamSQL 中编辑或删除特定连接

php - 如何将 php 导出为 pdf 一大查询?

mysql - 在一个查询中连接多行

php - 合并具有相同 pcode 的项目并计数为 1