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

时间:2018-09-08 06:33:56

标签: php mysql loops while-loop

我的while循环有问题。所以我有这段代码,可以插入提要和具有特定随机代码的多个文件。 例如,我将此表命名为“ 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循环中重复代码,我只需要打印一次提要。这是我的代码:

<?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

如何实现? 并预先感谢!

3 个答案:

答案 0 :(得分:2)

最简单的解决方案是将查询更改为使用GROUP BY并在GROUP CONCAT上执行FILE

$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 '/')

Demo on Rextester

更新

PHP代码中还有一个错误,您在while循环之前设置$fetch = mysqli_fetch_array($q),然后对其不执行任何操作,因此您将丢失一行值。请尝试以下代码:

 $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>';
 }

答案 1 :(得分:1)

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

 $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_concat的更多信息,请参见此处GROUP_CONCAT comma separator - MySQL

答案 2 :(得分:0)

<?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;
                }
        }
    }



?>