2011-04-26 153 views
0

我切換(從可怕的和不安全的mysql_query)一個web應用程序,我的工作到PDO時遇到一些困難如何將現有的查詢適應新的格式。該查詢找出一個特定的文件類型的媒體項目:PDO參數SELECT語句循環條件

的GET的格式如下:JPG,PNG,GIF

(下面的代碼是逃避的東西,但已被簡化爲這個例子)

$query = "SELECT * FROM `media` WHERE `active` = '1' AND `thumb` IS NULL "; 
if($_GET['extensions']){ 
    $extensions = array_filter(explode(',',str_replace(' ','',strtolower($_GET['extensions'])))); 
    foreach($extensions as $extension){ 
     $extension_sql[] = "`type` = '$extension' "; 
    } 
    if(count($extension_sql) > 0){ 
     $query .= 'AND (' . implode('OR ', $extension_sql) . ')'; 
    } 
} 
$query .= "ORDER BY `created` DESC "; 
$result = mysql_query($query); 
while($media = mysql_fetch_array($result)){  
    // Do stuff 
} 

也許我會對此在一個完全向後方式,它應該使用IN()函數,但無論如何,我需要將其轉換爲一個參數PDO的語句,如:

$sth = $dbh->prepare("SELECT * FROM `media` WHERE `active` = '1' AND `thumb` IS NULL AND `type` IN(:set) ORDER BY `created` DESC "); 
$types = implode(',', array_filter(explode(',',str_replace(' ','',strtolower($_GET['extensions'])))); 
$sth->bindParam(':set', $types); 
$sth->execute(); 
while($datatype_option_row = $sth->fetch()){ 
    // Do stuff 
} 

顯然,這是不行的......但我想成爲高效,安全的收效甚微。我也許能遍歷文件類型,以在結合重新創建SQL,然後循環......但想看看是否有人在這裏爲不同的方法有明智的建議。

TL; DR:試圖找到SQL參數化條件句的動態列表的最佳方式。

在此先感謝!

回答

0

想通了,關鍵是FIND_IN_SET功能,因爲它的類型的簡短列表:

$type_sql = ($_GET['extensions'])? "AND FIND_IN_SET(`type`, :type)" : ""; 
$sth = $dbh->prepare("SELECT * FROM `media` WHERE `active` = '1' AND `thumb` IS NULL $type_sql ORDER BY `created` DESC "); 
$sth->bindParam(':type', $_GET['extensions']); 
$sth->execute(); 
while($media = $sth->fetch()){ 
    // Do stuff 
}