2010-04-14 118 views
2

我正在建立一个字符串,我检查mysql数据库。php mysql查询字符串数组

eg: 
formFields[] is an array - input1 is: string1 
array_push(strings, formFields) 
1st string and mysql query looks like this: 
"select * from my table where id in (strings)" 

formFields[] is an array - input2 is: string1, string2 
array_push(strings, formFields) 
2nd string and mysql query looks like this: 
"select * from my table where id in (strings)" 

formFields[] is an array - input3 is: string1, string2,string3 
array_push(strings, formFields) 
3rd string and mysql query looks like this: 
"select * from my table where id in (strings)" 

我会想添加单引号和逗号阵列,这样我有这样的字符串数组: “从我的表中选择*,其中ID在(‘STRING1’,‘字符串2’,” string3')“

我试过使用数组implode,但仍然没有运气有任何想法?感谢

回答

6
'SELECT ... WHERE id IN ("' . implode('","', $strings) . '")'; 
+0

谢谢!奇迹般有效。 – NULL 2010-04-14 13:50:21

+0

工作得很好!我想问一个问题,正在做的点是什么,它们是否像“+”一样将引号与implode结果粘合起来? – deckoff 2012-10-29 20:44:34

+0

@deckoff Exacly。 – hsz 2012-10-29 21:41:53

0
implode("','",$array); 
+0

这不会在字符串的开始和结尾之前和之后添加引号。不管怎么说,还是要谢谢你! – NULL 2010-04-14 13:51:21

+0

@Chocho你也不知道连接?你迫切需要基本的PHP类。 – 2010-04-15 06:12:30

1

implode()是解决办法,但你不应该忘记转义数据:

$data = array(...); 
array_walk($data, function(&$elem, $key) { 
    $elem = mysql_real_escape_string($elem); 
}); 
$sql = 'SELECT ... id IN ("' . implode('", "', $data) . '");'; 
+0

也谢谢你,你的答案也是有效的! – NULL 2010-04-14 13:50:50