简体   繁体   English

在while循环中从表中选择每个PHP

[英]PHP for each on the while loop select from table

I'm having trouble with the following code. 我在使用以下代码时遇到麻烦。 I want to select from DB first and get some array, after that select from the same table based on each of the elements on the array. 我想先从数据库中选择一个数组,然后再根据该数组中的每个元素从同一张表中进行选择。

Problem 1: The second select while loop only returns one row from table wheres there are more than one rows matching what i'm selecting. 问题1:第二个select while循环仅返回表中的一行,其中有多行与我选择的行匹配。 I want to return five rows for each returned row from the first while loop. 我想从第一个while循环为每个返回的行返回五行。

Q.1 What's wrong with my code? Q.1我的代码有什么问题?

Problem two: I'm building an array from a column that has repeating contents. 问题二:我正在从具有重复内容的列中构建数组。 eg returned results might be: 例如,返回的结果可能是:

[Array]
1.John
2.Cane
3.Mary
4.John.

Now when john repeats, i get the same results as the one that was returned at '1'. 现在,当约翰重复时,我得到的结果与返回“ 1”的结果相同。 I know this is expected. 我知道这是预期的。

Q2: How do i avoid selecting the same contents in a row? 问题2:如何避免连续选择相同的内容?

Notes: i'm aware of the deprecated mysql. 注意:我知道过时的mysql。

PHP CODE PHP代码

<?php
require_once 'php/db_conx.php';
$log = mysql_query("SELECT * FROM ads WHERE section != ''") or die(mysql_error());
while ($row = mysql_fetch_array($log)) {
    $LibSection[] = $row['section'];
}
foreach ($LibSection as $Section) {
    $log2 = mysql_query("SELECT * FROM ads WHERE section = '$Section' limit 5") or die(mysql_error());
    include_once 'php/Random_color.php';
    while ($row = mysql_fetch_array($log2)) {
        echo '<a class="LibSectOpen">
<span style="display:none" class="SectionName">' . $Section . '</span>
<div class="LibrarySects"><div class="LibrarySectsHeader">' . $Section . '</div><div class="LibrarySectsShelf">
<div class="LibrarySectsShelf_Book" style="background-color:' . $Color . '" title="Author: ' . $row['bbookauthor'] . '">' . $row['bbookname'] . '</div></div></div></a>';
    }
}
?> 

I think you will be able to skip this problem by using MySQL DISTINCT operator. 我认为您可以使用MySQL DISTINCT运算符来跳过此问题。

Here is an useful tutorial: 这是一个有用的教程:

http://www.mysqltutorial.org/mysql-distinct.aspx http://www.mysqltutorial.org/mysql-distinct.aspx

You are required to choose distinct values so use it: 您需要选择不同的值,因此可以使用它:

SELECT DISTINCT * FROM Table_NAME where condition=value;

possible solution is W3schools.com- distinct example 可能的解决方案是W3schools.com-不同的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM