2

我在数据库中有 2 个表:

客户(显示所有客户数据)

clientsmany(管理员可以为每个客户添加许多电话号码)

我想在 1 个 html 表中打印有关客户的所有详细信息,如果任何客户有多个电话号码,所有号码都打印在“td”的同一个单元格中

<?php
$result = mysql_query("SELECT * FROM clients");
$result1 = mysql_query("SELECT clientsmany.phone, clients.ID FROM clients INNER JOIN clientsmany ON clients.ID=clientsmany.ClientID");

while($row = mysql_fetch_array($result)){ //Not read!
    while($row1 = mysql_fetch_array($result1)){ //Working correctly and show the list of 'phone' in $row1 for clientsmany.phone
echo "<center><table border='1'>";
echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."<br>".$row1['phone']."</td></tr>";
echo "</table></center>";
}}
?>

为什么第一时间不起作用?

第二次仅有效并打印正确的数据,然后自动退出!

4

3 回答 3

4
<?php
echo "<center><table border='1'>";
$result = mysql_query("SELECT * FROM clients");
 while($row = mysql_fetch_array($result)){
 $result1 = mysql_query("SELECT * FROM clientsmany WHERE clientsid=".$row['id']);
 if(mysql_num_rows($result1)>0 ){
 while($row1 = mysql_fetch_array($result1)){
 echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."<br>".$row1['phone']."</td>       </tr>";
}
}else{
 echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."</td></tr>";
}
}
echo "</table></center>";
?>
于 2013-10-06T19:24:57.280 回答
1

使用GROUP_CONCAT创建单个查询,您将能够进行单个循环

GROUP_CONCAT将采用重复的列并用逗号分隔每个值(默认情况下可以更改)并将其返回为单个值

$query = <<<END
    SELECT 
       clients.*,
       GROUP_CONCAT(clientsmany.phone) as phonenums 
    FROM 
      clients 
    INNER JOIN 
      clientsmany ON clients.ID=clientsmany.ClientID 
    GROUP BY 
      clients.ID 
END;

像这样的查询将为您提供所有客户表列和一个名为的列,该列phonenums将是电话号码的逗号分隔列表

现在,由于您只有一个查询,因此您只需要一个循环

$db = mysqli_connect(...);

...

//only need to echo out the <table> part once
//so taken out of the while loop
echo "<center><table border='1'>";

$result = mysqli_query($db,$query);
while( ($row = mysqli_fetch_assoc($result)) ) {
   echo <<<END
      <tr>
         <td>{$row['ID']}</td>
         <td>{$row['SomeOtherColumn']}</td>  
         <td>{$row['phonenums']}</td>
      </tr>
END;
}

//Again the </table> only needs done once 
//so taken out of the loop
echo "</table></center>";

注意正在使用的 mysli_* 函数。Mysql api 已被贬值,在大多数情况下,您可以将当前使用的函数重命名为 mysqli_,但请注意,有些需要$db链接作为参数,因此请务必阅读每个函数的 php 手册,以便知道如何调用他们正确。

另请注意,我使用的是heredoc语法,而不是执行多个 echo 调用

于 2013-10-06T04:50:29.357 回答
0

首先,mysql_*功能贬值。尝试使用mysqli_*函数。

如果你想在 1 个 html 表中显示数据,那么为什么要从while上面的table标签开始呢?

试试这个查询..

SELECT clientsmany.phone, clients.* FROM clients, clientsmany WHERE clients.ID=clientsmany.ClientID"

然后使用标签while下面的语句table(不需要2个不同的while循环)......

echo "<center><table border='1'>";
while($row1 = mysqli_fetch_array($result1))  {
   // your <tr><td> code
}
echo "</table></center>";
于 2013-10-06T04:34:32.437 回答