0

I have some PHP code to extract pupils from a database who have been assigned to the current user.

The query for extracting the pupils is:

$pupilsql = $db->prepare("SELECT * FROM pupil where id in (?)");
$pupilsql->bind_param("s", $dbpupils);
$pupilsql->execute();
$pupilresult = $pupilsql->get_result();

Where $dbpupils is a comma seperated list of student ID's (1,2,3 for example.)

However, the database will only return the pupil which matches the first ID in the list.

I have run the query with hard coded values like so:

$pupilsql = $db->prepare("SELECT * FROM pupil where id in (1,2,3)");

And can verify that it returns the 3 expected pupils.

I have also tried changing the bind_param data type to d instead of s to no avail.

Why will the query not return all 3 pupils when the ID's are stored in a variable?

Edit: My $dbpupils variable is not an array and so cannot be treated as one.

  • Each student id needs to be a separate placeholder in the array passed to `$pupilsql->execute()`. – Zhorov Jul 21 '20 at 13:58
  • 1
    With your example and only 1 `?`, the statement will look like `SELECT * FROM pupil where id in ('1,2,3')` – Nigel Ren Jul 21 '20 at 13:59
  • `My $dbpupils variable is not an array and so cannot be treated as one.` then you need to transform your string variable into an array. 1 variable will be treated as a single value that has numbers and commas in it, not multiple values. This is the difference between parameter binding and string interpolation. – Shadow Jul 21 '20 at 16:31

0 Answers0