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 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析