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.

2

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

@xingtan This is the final solution, I've read through and fixed the entire code correctly.
@xingtan glad it worked, make sure to tick the answer as the solution for others to notice if they come across the same problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.