duanhan4763 2016-10-10 23:29
浏览 287

MySQL SELECT WHERE IN数组[重复]

This question already has an answer here:

I have a situation where I'd like to add a list of names in an array and use it in an SQL query.

How I do it:

$names = implode(',', $names);
$sql = "DELETE FROM product WHERE name NOT IN ($names)";

This works ok if I use id (but I can't do that here). Problem is - name can have a comma in it (i.e. - benchpress rack, blue) and that breaks this query. Is there a way to bypass this issue?

</div>
  • 写回答

1条回答 默认 最新

  • dongxiezhuo8852 2016-10-10 23:36
    关注

    Try this:

    $names = implode("','", $names);
    $sql = "DELETE FROM product WHERE name NOT IN ('$names')";
    

    If this is your actual code I would suggest switching to PDO, use a library, or escape your values with mysqli_real_escape_string.

    Here is a link: http://php.net/manual/en/mysqli.real-escape-string.php

    Here is a w3schools link for prepared statements, a decent high level view of how they work: http://www.w3schools.com/php/php_mysql_prepared_statements.asp

    Here is how your statement query will run if your using PDO:

    $query= $conn->prepare("DELETE FROM product WHERE name NOT IN (:names)");
    $query->bindParam(':names', $names);
    $query->execute();
    

    And for mysqli it will be similar, refer to the w3schools link above for the differences.

    I highly recommend you move away from the old mysql driver and at the very least switch to mysqli.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么