繁体   English   中英

从表中检索不同的值

[英]Retrieve distinct values from table

我必须打印一次客户名称以及每个客户的所有产品。我的代码如下。

 <div id="Allproducts">
 <?php
  $AllprodsRes = $conn -> query("select * from sepproducts");
  if($AllprodsRes ->num_rows > 0){
    $result = $AllprodsRes -> fetch_array(); 
  ?>
    <label for="name"><?php echo $result['name'] . " " . $result['surname']; ?></label>
  <?php } ?>
  <?php do{ ?>

  <p><?php echo $result['product_name'] . " " //$result['count']; ?></p>  
 <?php }while($result = $AllprodsRes -> fetch_array()); ?>
 </div>

查看sepproducts

CREATE 
    ALGORITHM = UNDEFINED 
    DEFINER = `root`@`localhost` 
    SQL SECURITY DEFINER
VIEW `sepproducts` AS
    select 
        `customers`.`name` AS `name`,
        `customers`.`surname` AS `surname`,
        `custproducts`.`product_name` AS `product_name`,
        count(0) AS `count`
    from
        (`custproducts`
        join `customers` ON ((`custproducts`.`custid` = `customers`.`custid`)))
    group by `custproducts`.`product_name`

任何帮助都值得欢迎和赞赏。 提前致谢。

您可以使用类似于以下内容(假设您使用MySQLi):

<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');

$currentCustomer = null;
while ($result = $query->fetch_array()) {
    $name = $result['name'] . ' ' . $result['surname'];

    // Check to see if we're working with a new customer.
    if ($currentCustomer != $name) {
        echo $name . '<br />';
        $currentCustomer = $name;
    }

    echo $result['product_name'] . '<br />';
    echo $result['product_type'] . '<br />';

    // ETC.
}
?>

或者,如果您只担心一个客户,请使用以下方法:

<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');

if ($query->num_rows > 0) {
    $result = $query->fetch_array();

    echo $result['name'] . ' ' . $result['surname'] . '<br />';

    do {
        echo $result['product_name'] . '<br />';
        echo $result['product_type'] . '<br />';

        // ETC.
    } while ($result = $query->fetch_array());
}
?>

实际上,它检查是否已找到记录,如果找到,则将一个结果写入数组$ result。 然后,我们输出循环的客户名称OUTSIDE(因此,该名称仅发生一次),然后使用do ... while()循环继续遍历结果数组的其余部分。

我希望这有帮助!

根据您使用的数据库,您可以将多行合并为一个列。 最终这是一个显示问题。 我说要继续做您正在做的事情,并在您的视图中跟踪循环中的当前名称并与下一个名称进行比较-如果名称相同,则忽略它,当名称不同时将current_name设置为该新名称并继续。 这样,每个名称仅显示一次。

暂无
暂无

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

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