MySQL查询转义单引号

时间:2019-05-30 16:54:45

标签: mysql escaping quote

我对以下db :: insert命令有问题。 我想在mysql查询中的()部分中使用数组,但是逗号已转义。我该如何解决这个问题?

$users = [435,1671,429];
$list = implode("','", $users);

DB::insert("insert into ".
    "rejections (calendar_id, user_id, note, status) ".
    "select id as calendar_id, ?, concat(?), concat(?) ".
    "from calendar ".
    "where DATE(_date) BETWEEN ? AND ? and user_id in (?)", [$admin, $note, $status, $start_date, $end_date, $list]
);
  

mysql_log:2019-05-30T16:28:51.221007Z 1815执行拒绝插入(calendar_id,user_id,note,status)选择id作为calendar_id,2416,concat('Comment'),concat(1) DATE(_date)在'2019-05-01'和'2019-05-31'之间以及(_435 \,\'1671 \',\'429')中的user_id

1 个答案:

答案 0 :(得分:0)

一种快速(又肮脏)的解决方法是删除implode()中的单引号,并使用FIND_IN_SET()而不是IN()

$users = [435,1671,429];
$list = implode(",", $users);

DB::insert("insert into ".
    "rejections (calendar_id, user_id, note, status) ".
    "select id as calendar_id, ?, concat(?), concat(?) ".
    "from calendar ".
    "where DATE(_date) BETWEEN ? AND ? and find_in_set(user_id, ?)"
, [$admin, $note, $status, $start_date, $end_date, $list]);

请注意,这可能会比较慢,因为无法使用user_id上的索引。

如果要在查询中使用IN(),则需要为每个用户使用一个占位符:

IN (?,?,?)

并绑定每个用户ID

[$admin, $note, $status, $start_date, $end_date, $list[0], $list[1], $list[2]]

由于您可能事先不知道uf用户的数量,因此可以使用以下方式:

$users = [435,1671,429];

$usersPlaceholders = array_map(function($id) { return '?'; }, $users);
$usersPlaceholders = implode(',', $usersPlaceholders);
$params = array_merge([$admin, $note, $status, $start_date, $end_date], $users);

DB::insert("
    insert into rejections (calendar_id, user_id, note, status)
    select id as calendar_id, ?, concat(?), concat(?)
    from calendar
    where DATE(_date) BETWEEN ? AND ? and user_id in ($usersPlaceholders)
", $params);