php SQL 查询中的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5295714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array in SQL Query?
提问by njaknjak
i have a problem making a SQL Query with an array in my WHERE clause.
我在 WHERE 子句中使用数组进行 SQL 查询时遇到问题。
For example:
例如:
My Array:
我的阵列:
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
My MySQL Statement:
我的 MySQL 声明:
SELECT * FROM myTable WHERE title='".$myarray[]."'
Is there any way to realize that? I solved it myself like this:
有没有办法意识到这一点?我自己是这样解决的:
for(...) {
$where = $where." title='".$myarray[$count]."' OR ";
}
$where = substr($where , 0, -3);
.....
SELECT * FROM myTable WHERE ".$where."
But if i had thousands of entries in my array, the SQL Statement would be too big and slow, right?
但是如果我的数组中有数千个条目,那么 SQL 语句就会太大太慢,对吗?
Thanks
谢谢
回答by Tim
You can use mysql's IN-function
你可以使用mysql的IN函数
EDIT: As amosrevira said, you need to escape you strings in the array.
编辑:正如 amosrevira 所说,您需要对数组中的字符串进行转义。
$myarray[1] = "'hi'";
$myarray[2] = "'there'";
$myarray[3] = "'everybody'";
$newarray = implode(", ", $myarray); //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($newarray);
回答by Your Common Sense
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
//every quoted string should be escaped according to SQL rules
foreach($myarray as $key => $val) {
$myarray[$key] = mysql_real_escape_string($val);
}
$in_str = "'".implode("', '", $myarray)."'"; //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($in_str);
回答by Hamish
You can us the IN
operator. You want it to look like:
您可以联系我们的IN
运营商。你希望它看起来像:
title IN ('hi', 'there', 'everybody')
So you'd do something like:
所以你会做这样的事情:
$sql = "SELECT * FROM myTable WHERE title IN '" . implode("','", $myarray) . "';"
Note that you need to filter your array for SQL injection issues first.
请注意,您需要首先针对 SQL 注入问题过滤数组。
回答by Muthu Kumaran
You can try use of IN
in your WHERE
clause,
你可以尝试IN
在你的WHERE
条款中使用,
SELECT * FROM myTable WHERE title IN ('hi', 'there', 'everybody');
or
或者
SELECT * FROM myTable WHERE title IN ('.implode(',', $myarray).');