简体   繁体   English

连续打印同一张表中的不同数据

[英]print different data from same table in a row

Hi i want print differt data from same table with PHP.嗨,我想用 PHP 从同一张表中打印不同的数据。 My table is:我的桌子是:

Table A:
     ID    name
-----------
     111    Giovanna
     111    Jenny
     112    John
     113    Rick

I want this output:我想要这个 output:

Mansioni: 111   People:Giovanna,Jenny
          112   People:John
          113   People:Rick

My code php:我的代码 php:

$codice=$_GET['id'];  //id is is chosen by the user
$query1="select distinct ID from A where ID= '".$codice."'";
$query2="select distinct name from A where ID= '".$codice."'";
$query_imp = pg_query($conn1, $query1);
$query_impiegati = pg_query($conn1, $query2);
    echo 'Mansioni: ';
        while($row1 = pg_fetch_array($query_imp)){
        while($row2 = pg_fetch_array($query_impiegati)){ ;
            echo '</table>';
                echo '<tr>
                <td>'.$row1['ID'].' 
                 &nbsp;&nbsp;&nbsp;&nbsp;People:'.$row2['name'].'<br></td> 
                </tr>';
                echo '</table>';
                }
            
}

My code don't work.How can i do?我的代码不起作用。我该怎么办?

A SQL result will almost always be a 2D array, so you need to do a "post-processing" after the request to transform your data. SQL 结果几乎总是二维数组,因此您需要在请求后进行“后处理”以转换数据。 The idea is to use a associative array as dictionary.这个想法是使用关联数组作为字典。

/* 
  the SQL request will give your an array like : 
  [
    ['ID' => 111, 'name' => 'Giovanna'],
    ['ID' => 111, 'name' => 'Jenny'],
    ['ID' => 112, 'name' => 'John'],
    ['ID' => 113, 'name' => 'Rick']
  ]

  you want to transform it to something like :
  [
    '111' => ['Giovanna', 'Jenny'],
    '112' => ['John'],
    '113' => ['Rick']
  ]
*/

$codice=$_GET['id'];  //id is is chosen by the user
$query="select ID, name from A where ID= '".$codice."'";
$query_imp = pg_query($conn1, $query);
$dataById = [];
while($row = pg_fetch_array($query_imp)) {
  /* loop on each row */
  if(empty($dataById[$row['ID']) {
     /* if the entry of the dictionary is empty, initialize a empty array
     $dataById[$row['ID'] = [];
  }
  /* add the current name to the right entry */
  $dataById[$row['ID'][] = $row['name'];  
}

/* Text Rending */
foreach($dataById as $id) {
    echo $id . "     People:" . implode(',', $dataById[$id]);
}

I'm using an associative array to classify your data based on the ID.我正在使用关联数组根据 ID 对数据进行分类。 And impode to transform an array to a string.impode将数组转换为字符串。

Beware of the us of concatenation in SQL query: it's absolutely forbidden in production due to security breach.注意 SQL 查询中的连接我们:由于安全漏洞,在生产中绝对禁止。 Search for "SQL injection".搜索“SQL 注入”。

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

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