将具有列 ID 的 MySQL 字符串绑定到 PHP 数组中的该 ID


Binding MySQL strings that have a column ID to that ID in PHP array

>我有一个由默认键中的 ID 组成的数组,我想将这些 ID 与由这些 ID 组成的 MySQL 表中的相应描述以及不同列中的描述相关联。下面的表和数组示例:

Array
(
[0] => 1
[1] => 12
[2] => 17
[3] => 21
[4] => 26
)
+----+----------------------------+
| ID | description                |
+----+----------------------------+
| 1  | Example Description        |
+----+----------------------------+
| 2  | Wow, this is a description |
+----+----------------------------+
| 3  | Amazing description        |
+----+----------------------------+
| 4  | Description for ID4        |
+----+----------------------------+
| 5  | Yes, another description   |
+----+----------------------------+

输出必须如下所示(带或不带逗号):

Description, Another description, description...

数组名为"$arraymanutenzionehwos",表名为"interventi_hwos"

我已经提供了一般情况,但如果需要,我可以提供我的代码和所有需要的细节。

脚本的主要过程是在数组的每个元素中选取 ID,并将其绑定到 Mysql 表列中的正确描述。

多谢

我认为您想使用这样的查询:

 SELECT GROUP_CONCAT(DISTINCT description ORDER BY description SEPARATOR ', ' ) AS d
   FROM interventi_hwos
  WHERE id IN (1,12,17,21,26)

这将生成一行,其中包含一列,其中包含所需的逗号连接字符串。

要从 php 执行此操作,您需要执行类似操作来组合查询字符串。

$query = <<< 'ENDQUERY'
SELECT GROUP_CONCAT(DISTINCT description ORDER BY description SEPARATOR ', ' ) AS d
  FROM interventi_hwos
 WHERE id IN 
ENDQUERY
$query .= ' (' . implode( ',', array_filter($arraymanutenzionehwos, 'is_int') . ')';

请注意,这会通过从数组中删除任何非整数项来清理数组。这有助于防止SQL注入。

如果没有更多详细信息,很难提供完整的解决方案,但您可以使用以下查询:

$sql = "
SELECT description FROM interventi_hwos
WHERE id IN (" . implode(',', $arraymanutenzionehwos). ")
ORDER BY FIELD(id, " . implode(',', $arraymanutenzionehwos). ")
";

给定您的示例数据,这将生成如下查询:

SELECT description FROM interventi_hwos
WHERE id IN (1,12,17,21,26)
ORDER BY FIELD (id, 1,12,17,21,26)

查看此查询的演示

这将根据数组中的 id 为您提供描述列表,顺序与原始 id 数组相同。您可以使用PHP来格式化生成的数组。请注意,如果结果的顺序无关紧要,请删除 ORDER BY 子句。