如何在sql查询中使用动态数组

时间:2016-05-05 12:00:48

标签: php mysql arrays

我的查询:

SELECT MAX(num)
FROM (SELECT nomInteretUser,idUser,COUNT(nomInteretUser) as num
      FROM userInteret
      WHERE nomInteretUser IN ('piano','flute','chien') GROUP BY idUser
     )

目标是将IN ('piano','flute','chien')更改为动态数组 喜欢

SELECT nomInteretUser, idUser, COUNT(nomInteretUser) as num
FROM userInteret
WHERE nomInteretUser IN ($array)
GROUP BY idUser

注意:$ array是一个包含interet列表的数组

2 个答案:

答案 0 :(得分:2)

使用implode()。试试下面的代码。您需要将数组转换为字符串。所以在这里我们将使用逗号分隔,例如','字符串,并在查询中使用它来破坏它。

$array =array('piano','flute','chien');

$string = implode("','", $array);

$query = "SELECT nomInteretUser, idUser, COUNT(nomInteretUser) as num
FROM userInteret
WHERE nomInteretUser IN ('".$string."')
GROUP BY idUser";

在线观看演示:Click Here

答案 1 :(得分:2)

您可以使用implode()功能。

implode()函数将连接数组,如:piano','flute','chien

我们需要单引号以及开头和结尾。

因此,请在implode()之前和之后添加:"'".implode("','",$array)."'"

$array = array('piano','flute','chien');
WHERE nomInteretUser IN('".implode("','",$array)."')";

Working Demo