查询内部循环

时间:2015-01-22 17:21:43

标签: php loops pdo

所以我有一个功能,允许我根据他的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"];
    }
}

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

2 个答案:

答案 0 :(得分:2)

使用此代码。

它将获取所有玩家ID,然后只运行一个查询,以获取所有玩家的所有记录,包括RUNNING MULTIPLE查询。

<?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'];

    }


}
?>

答案 1 :(得分:0)

我认为你真正想要的是LEFT JOIN,假设表1中的玩家字段等于表2中的ID字段。

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

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