如何在while循环中只打印一次帖子?

nuypyhwy  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(407)

我对while循环有问题。所以我有一个代码,插入feed和多个带有特定随机代码的文件。例如,我有一个名为“feed”的表

ID  | FEED      | FILE          | CODE
---------------------------------------
1   |Test post  |uploads/1.jpg  | 54231
2   |Test post  |uploads/2.jpg  | 54231
3   |Test post  |uploads/3.jpg  | 54231
4   |Test post  |uploads/4.jpg  | 54231

如果代码在while循环中重复,我只需要打印一次feed。这是我的密码:

<?php
	 $connect = mysqli_connect("localhost","root","","test");

	 // Check connection
	 if (mysqli_connect_errno())
	   {
	   echo "Failed to connect to MySQL: " . mysqli_connect_error();
	   }
	 $q = mysqli_query($connect,"SELECT * FROM feed");
	 $fetch = mysqli_fetch_array($q);
	 while($fetch = mysqli_fetch_array($q)) {

	echo '<div class="post">'.$fetch['feed'].$fetch['file].'</div><br>';

	 }
     ?>

以上代码输出:

Test postuploads/1.jpg
Test postuploads/2.jpg
Test postuploads/3.jpg
Test postuploads/4.jpg

我需要这样的东西:

Test post uploads/1.jpg / uploads/2.jpg/ uploads/3.jpg/ uploads/4.jpg

如何做到这一点?提前谢谢!

vshtjzan

vshtjzan1#

<?php
$connect = mysqli_connect("localhost","root","","test");

if (mysqli_connect_errno())
        {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
$q = mysqli_query($connect,"SELECT * FROM feed");                                                    
$fetch1 = mysqli_fetch_all($q);
$fetch2=$fetch1;

$fn1= count($fetch1);
$fn2=count($fetch2);

for($i=0;$i<$fn1;$i++)
    {        
        for($j=0;$j<$fn2;$j++)

        {
            if( $fetch1[$i][3] == $fetch2[$j][3])
                {
                    echo "duplicat";
                   echo "<div class='post'>";
                         print($fetch1[$i][1]);   print($fetch1[$i][2]); 
                    echo  "</div><br>";  

                    break 2;
                }
        }
    }

?>
uplii1fm

uplii1fm2#

尝试此查询这将按代码分组文件

$q = mysqli_query($connect,"SELECT GROUP_CONCAT(file, ' ') AS files,* FROM feed GROUP BY code");
 $fetch = mysqli_fetch_array($q);
 while($fetch = mysqli_fetch_array($q)) {

 echo '<div class="post">'.$fetch['feed'].' '.$fetch['files'].'</div><br>';

 }
 ?>

有关group\u concat的更多信息,请参见此处group\u concat逗号分隔符-mysql

ncecgwcz

ncecgwcz3#

最简单的解决方案是将查询更改为使用 GROUP BY 做一个 GROUP CONCATFILE :

$q = mysqli_query($connect,"SELECT FEED, GROUP_CONCAT(FILE) AS file, CODE FROM feed GROUP BY CODE");

这将给你一行每 CODE 输出值,如下所示:

FEED        FILE                                                         CODE
Test post   uploads/1.jpg, uploads/2.jpg, uploads/3.jpg, uploads/4.jpg   54231

如果你想要一个除 , 例如。 / ,更改 GROUP_CONCAT

GROUP_CONCAT(FILE SEPARATOR '/')

rextester上的演示
更新
php代码中还有一个错误,您正在设置 $fetch = mysqli_fetch_array($q) 在while循环之前,然后不使用它做任何事情,因此会丢失一行值。请尝试以下代码:

$q = mysqli_query( $connect, "SELECT FEED AS feed, GROUP_CONCAT(FILE) AS file, CODE FROM feed GROUP BY CODE" );
 while ( $fetch = mysqli_fetch_array( $q ) ) {
    echo '<div class="post">' . $fetch[ 'feed' ] . $fetch[ 'file' ] . '</div><br>';
 }

相关问题