2012-10-15 74 views
0

我目前使用下面的代碼片段搜索雖然DB庫MySQLi:尋找

for($i=0; $i<sizeof($deleted_records);$i++) { 

    if($stmt->prepare("SELECT `id`, `status` FROM `02-2012` WHERE `id` = ?")) { 

    // Bind your variable to replace the ? 
    $stmt->bind_param('s', $id); 

    // Set your variable  
    $id = $deleted_records[$i]; 

    // Execute query 
    $stmt->execute(); 

    // Bind your result columns to variables 
    $stmt->bind_result($id_f, $stat_f); 

    // Fetch the result of the query 
    while($stmt->fetch()) { 
     //echo $id_f . ' - ' . $stat_f . '<div>'; 
     array_push($hits, $id_f); 

    } 

}

其中

$deleted_records 

是在一個MySQL表數組的元素大陣列(基本上試圖在'02 -2012'表中找到陣列元素的所有出現)

T他用這種方法的問題是,它現在速度很慢。我確信有比這種強力方法更好/更優雅的方式。

感謝您的時間

回答

0

而不是使用PHP循環和執行查詢,每次可以使用IN條款,一旦執行查詢。

的問題是,我們不能這樣做:

if($stmt->prepare("SELECT `id`, `status` FROM `02-2012` WHERE `id` IN (?)")) { 

,我們需要有你想在 通過確保$deleted_records是一個數組的每個參數單獨的佔位符。 $qMarks是一串佔位符?,?,?,?,?

$qMarks = str_repeat('?,', count($deleted_records) - 1) . '?'; 
//Suggested by @DonamiteIsTnt (http://stackoverflow.com/questions/920353/php-pdo-can-i-bind-an-array-to-an-in-condition) 

if($stmt->prepare("SELECT `id`, `status` FROM `02-2012` WHERE `id` IN ($qMarks)")) { 

    $stmt->execute($deleted_records); 
} 

沒有測試。