dongqin5604 2014-12-13 20:52
浏览 23
已采纳

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

I have an array composed by IDs in default keys, I want to link these IDs with there correspondent description in a MySQL table composed by these IDs and the description in different columns. Example of the Table and Array below:

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   |
+----+----------------------------+

The output have to look like the following(with or without commas) :

Description, Another description, description...

The array is named '$arraymanutenzionehwos' and the table 'interventi_hwos'

I have provided general case, but if needed I can provide my code and all the needed details.

The main process of the script were to pick the ID in each element of the array and bind it to the proper description in the Mysql table column.

Thanks a lot

  • 写回答

2条回答 默认 最新

  • doutangxi2144 2014-12-13 21:15
    关注

    I think you want to use a query something like this:

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

    This will yield one row containing one column with the comma-concatenated string you want.

    To do that from php you're going to need to do something like this to put together your query string.

    $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') . ')';
    

    Notice that this sanitizes your array by eliminating any item from it that isn't an integer. That's helpful to prevent SQL injection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据