0

I am constructing a MySQL statement for a WHERE IN of varying length like so:

if(count($postTopics)) {
    $query = "SELECT `type` FROM `db` WHERE `id` = ".$_POST['id']." AND `topic` IN (";
    foreach ($postTopics as $name => $value) {
    $query .= "?,";
    }
    $query .= substr($query,0,-1);
    $query .= ")";      
}

$result = $mysqli->prepare($query);
if($result === FALSE) {
    die($mysqli->error);
}

The $postTopics variable is a slightly adjusted copy of the $_POST variable. Oddly, this code produces the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT type FROM exam_db WHERE course_id = 3 AND topic IN (?)' at line 1

There are related question regarding binding parameters dynamically, but note that the issue here is not related to bind_param -- the code doesn't make it that far.

Any tips would be much appreciated.

Levi
  • 301
  • 3
  • 12
  • 1
    `WHERE id = ".$_POST['id']."` By putting a raw user-supplied value in your SQL, you're defeating the purpose of having a prepared statement – Machavity Feb 05 '17 at 18:32
  • Plus, adding to Machavity's statement, that a nice place for some SQL query injection. :D – forrestmid Feb 05 '17 at 19:14
  • Yes please ignore that little bit for the time being. It's not the cause of the error + the $_POST variable is not external. I haven't yet figured out how input a hybrid set of bind_param parameters in the call_user_func_array() – Levi Feb 05 '17 at 19:59

0 Answers0