0

$multiples_names is an array.

For eg $multiple_names = ['1','2','3','4'];

How do I pass it to php mysql query so that I can select all items pertaining to that array.

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

I want the results of query to look something like that

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

Try a lot of methods but still could not get the results I want.

Zayn Ali
  • 4,765
  • 1
  • 30
  • 40
xingtan
  • 53
  • 1
  • 2
  • 7

1 Answers1

0

You can make placeholders depending on the size of $multiple_names_array. You should never put values directly into a query like in your code because (as said in the comments) you are vulnerable to SQL injection. I would also put all of the values into one array.

This is the solution you are looking for. All values are binded.

//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);
MinistryOfChaps
  • 1,458
  • 18
  • 31