PHP-向sql查询IN子句添加参数



我正在尝试将params添加到PHP中sql查询的IN子句中。

查询:

$sqlQuery = <<<SQL 
SELECT * FROM mytable where codes IN (:codes)"
SQL;

参数:

$params['codes'] = "'test','last'";

但这不起作用,即不会返回任何结果

$total = DB::select($sqlQuery, $params);

但是这个直接在数据库中运行的查询返回结果

SELECT * FROM mytable where codes IN ('test','last')

我猜这是因为参数的处理方式与IN子句不同,但我还没能找到任何关于这方面的信息。

如果您正在使用Laravel,并且如果原始sql不是必须的,那么您可以这样做。

DB::table("mytable")
->whereIn('codes', $param['codes'])
->get();

这将为您提供mytable行的相关集合。

如果你把模型正确地设置为Eloquent模型,你也可以这样做:

MyModel::whereIn('codes', $param['codes'])->get();

应该会产生同样的结果。

参考文献:Laravel文件,在";whereIn/whereNotIn/或whereIn/或whereNotIn";根据附加条款

尝试在sql查询中扩展数组和params。例如,sql查询应该像"SELECT*FROM mytable where codes IN(:param1,:param2(">,并使用数组$params['codes']上的扩展运算符传递params值。您可以使用foreach循环使其成为动态

不能像那样绑定列表。每个绑定变量都需要自己的占位符。我想你不会提前知道你会有多少参数。这样的方法是可行的,尽管这肯定是可以优化的。

$codes = ['test','last'];
$qry = sprintf('SELECT * FROM mytable where codes IN (%s)',
implode(',',array_filll(0, count($codes), '?')
);
$total = DB::select($qry, $codes);

最新更新