2012-04-09 81 views
0

我有一個ID爲$friends = array(0001, 0002, 0003, 0004)的數組,其中table_name = friendscolumn_header = fidfidfriends中可能包含或不包含其中一個朋友ID。我想在查詢中輸入$friends,並返回$friendsfid行中的所有當前值。從具有PDO的SQL數據庫中拉取數組值(PHP)

我敢肯定,fid={array_values($friends)}是錯誤的,但我不知道怎麼傳where部分數值數組...

//All DB_X's are defined in another file that is included in this actual file 
$db = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS); 
$stmt = $db->prepare("SELECT fid FROM friends WHERE fid={array_values($friends)} ORDER BY fid ASC"); 
$stmt->execute(); 

$friendResults = $stmt->fetchAll(); 

回答

1

您需要使用SQL的IN運營商:

SELECT ... FROM ... WHERE foo IN (val1, val2, ...) 

您可以使用PHP的implode()函數來獲得所需的SQL位:

$values = implode(', ', array_values($friends)); 
$query = "SELECT ... FROM ... WHERE fid IN ({$values})"; 

如果您的值是數字,上面的工作將會起作用。如果他們是字符串,你必須之前implode() ING修改值:

$values = array_map(array_values($friends), function($value) { 
    return "'{$value}'"; // Here is where you could do sanitization 
}); 
$values = implode(', ', $values); 

請注意:你必須在正確消毒$friends數據,以防止SQL注入。