php数组进入mysql select查询

时间:2017-08-08 07:44:07

标签: php mysql

$multiples_names是一个数组。

例如$multiple_names = ['1','2','3','4'];

如何将其传递给php mysql查询,以便我可以选择与该数组相关的所有项目。

$multiple_names = $_POST['multiple_names'];  

$multiple_names_array = implode(',', $multiple_names);

$stmt1 = $conn->prepare("SELECT * from attendance where name in (?) and today_date between ? and ? order by id ASC");

$stmt1->execute(array($multiple_names_array, $checkInDateFinal, $checkOutDateFinal));

我希望查询的结果看起来像那样

Names   Product
1       Product A
1       Product A
2       Product B
3       Product C
3       Product C
4       Product D

尝试了很多方法,但仍无法得到我想要的结果。

1 个答案:

答案 0 :(得分:0)

您可以根据$multiple_names_array的大小制作占位符。您不应该将值直接放入查询中,就像在代码中一样,因为(如注释中所述)您很容易受到SQL注入攻击。我还将所有值都放在一个数组中。

这是您正在寻找的解决方案。所有值都绑定

//Assuming the names are separated by commas, e.g "John,Jack,Jill';
$multiple_names = $_POST['multiple_names'];  
$multiple_names_array = explode(',',$multiple_names);

$placeholders = implode(', ',  array_fill(0, count($multiple_names_array), '?'));

//Put all values into one array.
$arguments = array_merge(array(), $multiple_names_array);
array_push($arguments, $checkInDateFinal);
array_push($arguments, $checkOutDateFinal);

// SELECT * FROM attendance WHERE name IN (?, ?, ?, ?, etc...) AND today_date BETWEEN ? AND ? ORDER BY id ASC
$stmt1 = $conn->prepare("SELECT * from attendance where name in ($placeholders) and today_date between ? and ? order by id ASC");
$stmt1->execute($arguments);