【问题标题】:MySQLi: searching for elements of array in a MySQL tableMySQLi:在 MySQL 表中搜索数组元素
【发布时间】:2012-10-15 09:55:55
【问题描述】:

我目前正在使用以下代码 sn-p 搜索数据库

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'表中找到该数组元素的所有出现)

这种方法的问题在于它非常缓慢。我确信有比这种蛮力方法更好/更优雅的方法。

感谢您的宝贵时间

【问题讨论】:

    标签: php mysql arrays mysqli


    【解决方案1】:

    您可以使用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);
    }
    

    没有测试。

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 1970-01-01
      • 2023-02-01
      • 2021-06-03
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      相关资源
      最近更新 更多