2012-01-03 123 views
0

我必须创建一条SQL命令,用于在数据库表中查找与我的数组中包含的某个字符串匹配的字符串。如何查找匹配数组中的字符串的字符串

//this is my array 
$liste_des_themes=array("Préfectures et sous-préfectures","Mairie","Banque"); 
$stmt = $this->db->prepare('SELECT * FROM etablissements where type IN $liste_des_themes');//i tried this but seems not working 
$stmt->execute(); 
$stmt->bind_result($id, $libelle); 
while ($stmt->fetch()) { 
    echo "$id $libelle<br/>"; 
} 
$stmt->close(); 
+1

试试...'$这个 - > DB->准备( “SELECT * FROM ETABLISSEMENTS凡类型('” .implode(“','”,$ liste_des_themes)。“');' – Rufinus 2012-01-03 15:50:46

+2

@Rufinus作为答案添加答案,澄清问题和见解作为评论 – 2012-01-03 15:51:59

回答

5

你需要创建一个IN列表中正确的格式:

$liste_des_themes=array("Préfectures et sous-préfectures","Mairie","Banque"); 
$in_list = "'".implode("','", $liste_des_themes)."'"; 
$stmt = 
$this->db->prepare('SELECT * FROM etablissements where type IN ('.$in_list.')'); 
+1

+1虽然我会添加一个'array_map('mysql_real_escape_string',$ liste_des_themes )'因为我不确定他是否真的只想查找这些静态文本片断:/另外:不要忘记'liste_des_themes'变量前面的'$' – Matmarbon 2012-01-03 15:55:41

+1

我会co注意看http://stackoverflow.com/questions/1534377/php-mysqli-where-in,这样你可以绑定你的数组内容,而不用担心SQL注入。 – cmbuckley 2012-01-03 15:55:46

+0

@Matmarbon @Matmarbon你可以编辑'$':-P – Neal 2012-01-03 16:00:41

相关问题