2009-08-31 78 views
1

我公司目前擁有價值(business_id的)數組傳遞一個數組到MySQL

可以說,它的

Array 
(
[0] => 12 
[1] => 14 
[2] => 15 
) 

什麼是使用這些值來獲得對相關行信息的最佳方式來自數據庫的每個business_id。

它可以是一個一個查詢是我的問題。很顯然,你可以做

$q = "select * from business where business_id = 12"; 
$rs = mysql_query($q); 

回答

11
$ids = array(1, 2, 3, 4); 

$ids = join(', ', $ids); 
$query = "SELECT * FROM business WHERE business_id IN ($ids)"; 
// $query => SELECT * FROM business WHERE business_id IN (1, 2, 3, 4) 

常用的SQL注入警告仍然適用,你可能要遍歷IDS首先要驗證或轉義。此外,如果您期望字符串而不是數字,請使用:

$ids = array('a', 'b', 'c', 'd'); 

$ids = join("', '", $ids); 
$query = "SELECT * FROM business WHERE business_id IN ('$ids')"; 
// $query => SELECT * FROM business WHERE business_id IN ('a', 'b', 'c', 'd') 
7

使用SQL操作中:

$sql = 'SELECT * FROM business WHERE business_id IN (' . implode(',', $values) . ')'; 
$rs = mysql_query($sql); 

注:如果值來自他們應該被消毒的客戶端,無論是與mysql_real_escape_string()或者,因爲這些數字,你可以使用intval()。例如:

$ids = array_map('intval', $values); 
$sql = 'SELECT * FROM business WHERE business_id IN (' . implode(',', $ids) . ')'; 
$rs = mysql_query($sql); 
3

您可以使用逗號作爲分隔符來加入數組,並使用SQL IN語句。

$businessIds = join(",", $array); 
$q = "select * from business where business_id IN ($businessIds)"; 
$rs = mysql_query($q);