我想在IN语句(sql)中使用一组id。但是,这只能在正确写入时才能完成,例如:IN(' 12',' 13',' 14')
如何将id数组更改为该格式?这意味着在每个数字周围添加引号,并在引号括起来的每个数字之后添加一个逗号,除了数组中的最后一个数字。
我的代码:
$parent = "SELECT * FROM `web_categories` WHERE `parent_id` = 13 AND published = 1";
$parentcon = $conn->query($parent);
$parentcr = array();
while ($parentcr[] = $parentcon->fetch_array());
foreach($parentcr as $parentid){
if($parentid['id'] != ''){
$parentoverzicht .= "".$parentid['id']."";
}
}
我后来想要这样使用它:
$project = "SELECT * FROM `web_content` WHERE `catid` IN ('".$parentoverzicht."') AND state = 1";
答案 0 :(得分:1)
你试过implode()吗?
使用", "
作为粘合剂。您必须自己编辑字符串,以便在开头和结尾添加"
。
答案 1 :(得分:1)
使用implode()..
<?php
$a1 = array("1","2","3");
$a2 = array("a");
$a3 = array();
echo "a1 is: '".implode("','",$a1)."'<br>";
echo "a2 is: '".implode("','",$a2)."'<br>";
echo "a3 is: '".implode("','",$a3)."'<br>";
?>
output->>>>>>>
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''
答案 2 :(得分:1)
或者,您可以使用单一联接查询,如下所示。
SELECT con.* FROM `web_content` as con LEFT JOIN `web_categories` as cat
ON con.catid=cat.id WHERE cat.parent_id=13 AND published = 1
答案 3 :(得分:1)
如果DB中的列类型是整数,则实际上不需要引用值,但如果不是,则可以使用array_map来引用数组中的每个项目,然后{{3用逗号连接它们:
<?php
$ids = [1, 2, 3, 4, 5];
$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$in_clause = array_map(function ($key) {
return "'$key'";
}, $ids);
$sql = str_replace('?', implode(',', $in_clause), $sql);
echo $sql;
结果:
SELECT * from mytable where id in ('1','2','3','4','5')
答案 4 :(得分:1)
将此作为单个查询执行! SQL引擎有各种各样的优化来处理表,并且在代码中进行循环通常会更加昂贵。
显而易见的查询是:
SELECT wc.*
FROM web_content wc
WHERE wc.catid IN (SELECT cat.id
FROM web_categories cat
WHERE cat.parent_id = 13 AND cat.published = 1
) AND
wc.state = 1;
答案 5 :(得分:1)
您可以这样做:
$ids = ['1','2','3','4']; //array of id's
$newArr = array(); //empty array..
foreach($ids as $ids)
{
$newArr[] = "'".$ids."'"; //push id into new array after adding single qoutes
}
$project = "SELECT * FROM `web_content` WHERE `catid` IN (".implode(',',$newArr).") AND state = 1"; /// implode new array with commaa.
echo $project;
这会给你:
SELECT * FROM `web_content` WHERE `catid` IN ('1','2','3','4') AND state = 1