PHP MySQL嵌套客户数据列表

时间:2013-03-22 03:09:06

标签: php mysql html-lists

我有一个嵌套列表,可以显示客户及其电话号码:

杰森

555 111-1111
555 222-2222

克里斯汀

555 333-3333

约翰

555 444-4444
555 555-5555
555 656-6666
但是,我在添加电子邮件时遇到了麻烦。此代码只是复制每个电话号码下的电子邮件,但我需要将电话号码和电子邮件分组到每个客户下面,如:

杰森

555 111-1111
555 222-2222
jason@jason.com
jason.alternative@jason.com 

克里斯汀

555 333-3333
kristen@kristen.com
kristen.alternative@kristen.com
kristen.personal@kristen.com

约翰

555 444-4444
555 555-5555
555 656-6666
john@john.com

PHP代码:

<?php
$result = mysqli_query($dbc,"
SELECT 
fname, 
phone, 
email
FROM 
customer, 
phone, 
email, 
customer_phone, 
customer_email
WHERE
customer.id=customer_phone.customer_id
AND
phone.id=customer_phone.phone_id
AND
customer.id=customer_email.customer_id
AND
email.id=customer_email.email_id
order by fname
");

$oldname = null;
while($row = mysqli_fetch_array($result))
{
    if($oldname != $row['fname'])
    {
        echo "<h3>".$row['fname']."</h3>";
        $oldname = $row['fname'];
    }
    echo "<p>".$row['phone']."</p>";
    echo "<p>".$row['email']."</p>";
}
?>

1 个答案:

答案 0 :(得分:1)

此查询将在电话号码后插入电子邮件,首先获取电话号码,然后输入电子邮件。带有“1-Phone”和“2-Email”的列可确保电子邮件在电话号码后排序。

SELECT fname, '1-Phone' AS InfoType, phone AS TheInfo
  FROM Customer
  INNER JOIN phone ON phone.id=customer_phone.phone_id
  INNER JOIN customer_phone ON customer.id=customer_phone.customer_id
UNION SELECT fname, '2-Email', email
  FROM Customer
  INNER JOIN email ON email.id=customer_email.email_id
  INNER JOIN customer_email ON customer.id=customer_email.customer_id
ORDER BY fname, InfoType

我将连接更改为ANSI语法,因为它使我更容易处理这个问题;没有其他原因。如果这是您的偏好,请随意将连接条件推回到WHERE子句 - 我对此不感到强烈:)

渲染代码的唯一变化是替换它......

echo "<p>".$row['phone']."</p>";
echo "<p>".$row['email']."</p>";

......用这个:

echo "<p>".$row['TheInfo']."</p>";