这是antivirus_detail表:
+-----------------------------+--------------+------+-----+---------+-----------
| Field | Type | Null | Key | Default | Extra
|
+-----------------------------+--------------+------+-----+---------+-----------
| Emp_id | int(11) | YES | MUL | NULL |
| Computer_id | int(11) | YES | MUL | NULL |
| Antivirus_id | int(11) | NO | PRI | NULL |auto_incre
ment
| Antivirus_name | varchar(50) | YES | | NULL |
| Antivirus_key | varchar(50) | YES | | NULL |
| Antivirus_installation_date | date | YES | | NULL |
| Antivirus_expiration_date | date | YES | | NULL |
这是hardware_description表:
+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| Computer_id | int(11) | NO | PRI | NULL | auto_increment |
| Emp_id | int(11) | NO | MUL | NULL | |
| PC_type | varchar(20) | YES | | NULL | |
| Operating_system | varchar(20) | YES | | NULL | |
| Product_key | varchar(30) | YES | | NULL | |
| Assign_date | date | YES | | NULL | |
Emp_id是来自不同员工表和这两个表的外键。 Computer_id是hardware_description表中防病毒表中的外键。
这是我的PHP代码:
<?php require_once 'includes/dbconnection.php'; ?>
<?php require_once 'includes/functions.php'; ?>
<?php
$id="1";
$sql ="SELECT b.*, c.* FROM hardware_description b, antivirus_detail c WHERE b.Computer_id = c.Computer_id AND c.Emp_id = '$id'";
$result = mysqli_query($connection, $sql);
//var_dump($result);
?>
<table cellpadding="5" border="0">
<tr>
<th style="text-align: left;">Employee ID</th>
<th style="text-align: left;">Computer ID</th>
<th style="text-align: left;">Operating System</th>
<th style="text-align: left;">PC Type</th>
<th style="text-align: left;">Antivirus ID</th>
</tr>
<?php while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $row['Emp_id']; ?></td>
<td><?php echo $row['Computer_id']; ?></td>
<td><?php echo $row['Operating_system']; ?></td>
<td><?php echo $row['PC_type']; ?></td>
<td><?php echo $row['Antivirus_id']; ?></td>
</tr>
<?php
}
?>
</table>
现在,显示:
Employee ID Computer ID Operating System PC Type Antivirus ID
1 2 Windows XP Desktop 1
1 2 Windows XP Desktop 2
我希望输出如下:
Employee ID Computer ID Operating System PC Type Antivirus ID
1 2 Windows XP Desktop 1,2
我希望所有攻击计算机ID的防病毒ID都显示为数组。我如何实现这一目标?
答案 0 :(得分:3)
在您的查询中,您必须使用GROUP_CONCAT
来连接Antivirus_ids。
将您的SQL查询更改为类似的内容;
$sql ="SELECT b.Emp_id, b.Computer_id, b.Operating_system, b.PC_type, GROUP_CONCAT(c.Antivirus_id SEPARATOR ', ') as concatenated_ids FROM hardware_description b, antivirus_detail c WHERE b.Computer_id = c.Computer_id AND c.Emp_id = '$id' GROUP BY c.Antivirus_id";
在获取数据时,请将此$row['Antivirus_id'];
更改为$row['concatenated_ids'];
。