简体   繁体   English

通过内插数组来运行Where IN,但是输出是字符串,并且无法按预期在MySQL中运行

[英]Running Where IN by imploding an array, but output is a string and does not run in MySQL as expected

Trying to a run a simple select query with WHERE IN on a couple ID's. 尝试对夫妇ID使用WHERE IN运行简单的选择查询。

$idArray = array(492, 493, 494, 495);
$csvList = implode(",", $idArray);

DB::select("SELECT id, name FROM table WHERE id IN (?)", array($csvList));

That's what I'm running, no errors. 那就是我正在运行的,没有错误。 The problem is, my query outputs $csvList as a string with quotes. 问题是,我的查询将$csvList输出$csvList带引号的字符串。 '492, 493, 494, 495' which MySQL does not interpret properly. '492, 493, 494, 495'这MySQL不正确地解释。 I only get 1 result back for 492 instead of all 4 results. 我只得到492 1个结果,而不是全部4个结果。 If I remove the quotes from the query, it works fine. 如果我从查询中删除引号,则可以正常工作。

This is the full query that runs with the page: 这是与页面一起运行的完整查询:

SELECT id, name FROM table WHERE id IN ('491,493,494,495');

I need to get rid of the quotes, anyone know how I can do that? 我需要删除引号,有人知道我该怎么做吗? Or what I'm doing wrong? 还是我做错了什么?

You have two options. 您有两个选择。

Either use Laravel's query builder: 使用Laravel的查询构建器:

$ids = [492, 493, 494, 495];

$results = DB::table('table')->select('id', 'name')->whereIn('id', $ids)->get();

Or create an array of question marks, and implode them: 或创建一个问号数组,然后将其内implode

$ids = [492, 493, 494, 495];

$placeholders = implode(', ', array_fill(0, count($ids), '?'));

$results = DB::select("SELECT id, name FROM table WHERE id IN ({$placeholders})", $ids)->get();

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

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