简体   繁体   English

将变量传递给sql WHERE IN子句

[英]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. 我有一个复选框列表,用于将文章ID存储为值。 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"). 这意味着当用户选中一个复选框时,id会被存储为字符串并发送给处理程序(类似这样:“blah,blah,blah”)。 I will later delete the ids from the database. 我稍后会从数据库中删除ID。

My sql statement looks something like this: "delete from article where art_id in (".$_GET['art_id'].")" 我的sql语句看起来像这样:“从文章中删除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' " 当然,这不起作用,因为$ _GET ['art_id']看起来像“等等,等等,等等,而不是''等等','等等','等等','等等'”

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: Sanitize,implode然后插入字符串:

$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 如果$ _GET ['art_id']为空,您可能需要执行其他检查,例如提供默认值或仅在您拥有ID时进行查询

You are looking for implode function 您正在寻找内implode功能

See here 看这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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