MySQLi:在MySQL表中搜索数组元素

时间:2012-10-15 09:55:56

标签: php mysql arrays 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

是一个大型数组(基本上试图找到'02 -2012'表中所有出现的数组元素)

这种方法的问题在于它的速度很慢。我相信有比这种蛮力方法更好/更优雅的方式。

感谢您的时间

1 个答案:

答案 0 :(得分:0)

每次使用IN子句并执行一次查询时,而不是使用PHP循环并执行查询。

问题是我们不能做类似的事情:

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);
}

没试过。

相关问题