简体   繁体   中英

Passing variable to sql WHERE IN clause

I've viewed a few similar posts regarding this topic, but I haven't found them to work for me.

I have a list of checkboxes that store article ids as a value. This means when the user checks a checkbox, the ids are stored as a string and sent to the handler (something like this: "blah,blah,blah"). I will later delete the ids from the database.

My sql statement looks something like this: "delete from article where art_id in (".$_GET['art_id'].")"

Of course, this doesn't work because $_GET['art_id'] looks like "blah,blah,blah,blah" rather than " 'blah', 'blah', 'blah', 'blah' "

Some answers on the net mentioned spliting the string and using regex. I'm not sure what the best way is. If I wasn't clear on something, please ask and I'll clarify. Much thanks.

Sanitize, implode and then insert the string:

$ids = array();
$in = '';
if(isset($_GET['art_id']){
  foreach($_GET['art_id'] as $id){
    $ids[] = intval($id);
  }
  $in = implode(',', $ids);
}

$query = "delete from article where art_id in (".$in.")";

You might want to do additional checking in case where $_GET['art_id'] is empty, something like providing a default value or making the query only if you have the IDs

You are looking for implode function

See here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM