2012-11-19 48 views
0

我想搜索MySQL數據庫,將列列表與數組進行比較。我將如何做到這一點,可能全部在MySQL內部?我如何在MySQL中編寫這個?

這裏就是我想在PHP做:

<?php 
$array = array("a", "b", "c", "d"); 
// 'c' doesn't exist in the database 
$result = $this->mysqli->query("Query"); 
// Result should be array("a", "b", "d") 
?> 

我將如何做到這一點?

+0

使用框架或ORM,這種事情可能非常容易。任何直接使用'mysqli'都會導致困難的原因? – tadman

回答

0

你可以用the IN clause來做到這一點。

SELECT * FROM <table> WHERE <col> IN <array> 
0

試試這個:

// The array 
$array = array("a", "b", "c", "d"); 

// This takes the array and puts it into a string like "a,b,c,d" 
$array_for_query = implode(',', $array); 

$result = $this->mysqli->query("SELECT * FROM table WHERE the_letter IN ({$array_for_query})"); 

分別替換tablethe_letter與表和列名。

+2

不要忘記,您不能相信查詢中的用戶數據。如果您使用從用戶收集的數據數據,請務必在將數據直接填充到查詢中之前使用mysqli_real_escape_string將其轉義。這可以防止SQL注入攻擊。 – jtv4k