douju1928 2011-08-09 00:35
浏览 13
已采纳

php,mysql多查询

I need to optimize a script for high performance so the question is how can I add mysql multi-query to this code ?

  foreach($multiContent as $htmlContent) {
    $email = urldecode($email['1']);
    $user = $user['1'];

    //store in db
    $db->query("UPDATE eba_users 
                   SET mail = '$email' 
                 WHERE username = '$user'");
    //echo "email is $email and user is $user
";
  }

  //close if ($array_counter % 200
  unset($array_counter);
  unset($data);
}

  • 写回答

1条回答 默认 最新

  • doushi7314 2011-08-09 00:40
    关注

    If you're using mysqli or PDO already, you should be using prepared statements for your queries since they are supported. This will also have a slight increase in performance since the entire query doesn't need to be sent again to the DB server. However the biggest advantage is the increased security that prepared statements provide.

    Other than this, try adding an index on username to speed this query up if you haven't already.

    Edit: If you want to do it all in one query, as you seem to suggest, you could also use ON DUPLICATE KEY UPDATE as mentioned as an answer to this question:

    INSERT INTO eba_users (`username`, `mail`) 
    VALUES 
        ('username1','$email1'),
        ('username2','$email2'),
        ('username3','$email3'),
        ('username4','$email4'),
        ....
        ('usernameN','$emailN'),
    ON DUPLICATE KEY UPDATE `mail`=VALUES(mail);
    

    However this may not be as fast as using prepared statements with a regular UPDATE.

    Edit2: As requested, here is probably a close approximation of what you should be doing to bind the parameters in mysqli:

    if ($stmt = $mysqli->prepare("UPDATE eba_users SET mail= ? WHERE username= ?")) {
    
        /* loop through array of users */
        foreach ($array as $username => $newemail) {
    
            /* bind parameters for markers */
            $stmt->bind_param("ss", $newemail, $username);
    
            /* execute query */
            $stmt->execute();
        }
    }
    

    Of course this doesn't provide any sort of error messages in case this fails. For that, you can look into mysqli::error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端