查询内循环

Query inside loop

所以我有一个功能可以让我根据玩家的 ID 获得一些关于玩家的额外信息。

function get_player_details($id,$select="*") {
    include("includes/database.php");
    $results = $db->prepare("SELECT " . $select . " FROM `wp_users` WHERE `ID` = ?");
    $results->bindParam(1,$id);
    $results->execute();
    $player = $results->fetch(PDO::FETCH_ASSOC);

    if ($player === false){
      return $player;
    } else {
      return $player;
    }
}

然后我尝试在循环中使用函数:

$sql = "SELECT * FROM `unban_requests` WHERE `Player` = :player && `solved` = :solved";
$preparedStatement = $db->prepare($sql);
$preparedStatement->execute(array(
                    ':player' => $logged_info["ID"],
                    ':solved' => 0
                ));
$data = $preparedStatement->fetchAll();
if($data !== false && $preparedStatement->rowCount() > 0){
    foreach($data as $row) {
        $info = get_player_details($row["player"],"`username`");
        echo $info["username"];
    }
}

一切正常,问题是在循环中进行查询会使页面加载速度太慢。如何优化我的代码?

使用此代码。

它将获取所有玩家 ID,然后 运行 只有一个查询来获取所有玩家的所有记录,而不是 运行 多个查询。

<?php

function get_player_details($id,$select="*") {
    include("includes/database.php");

    // implode() will generate your IDs like  12, 122, 23
    $query = "SELECT " . $select . " FROM `wp_users` WHERE `ID` IN( " . implode(", " , $all_player_ids) . ");"
    echo $query;
    $results = $db->prepare($query);

    $results->execute();
    $player = $results->fetch(PDO::FETCH_ASSOC);

    if ($player === false){
      return $player;
    } else {
      return $player;
    }
}






$sql = "SELECT * FROM `unban_requests` WHERE `Player` = :player && `solved` = :solved";
$preparedStatement = $db->prepare($sql);
$preparedStatement->execute(array(
                    ':player' => $logged_info["ID"],
                    ':solved' => 0
                ));
$data = $preparedStatement->fetchAll();
if($data !== false && $preparedStatement->rowCount() > 0){

    $all_player_ids = array();
    // Get all the Player IDs and append to array
    foreach($data as $row) {
        $all_player_ids[] = $row['player'];
    }


    $all_player_usernames = get_player_details($all_player_ids, "username");

    foreach($all_player_usernames as $arr){
        echo $arr['username'];

    }


}
?>

我认为您真正想要的是 LEFT JOIN,假设 table 1 中的玩家字段等于 table 2.

中的 ID 字段

SELECT * FROM `unban_requests` WHERE `Player` = :player && `solved` = :solved LEFT JOIN `wp_users` ON unban_requests.player=wp_users.ID;

另一个加速是在字段 playersolved 上创建索引(如果您还没有)。