Php准备方法我应该在哪里使用While循环

I am new to PHP prepare method, I need some help to use while loop in the following code.

Here is the query function

function query($query, $bindings, $conn) {
    $stmt = $conn->prepare($query);
    $stmt-> execute($bindings);
    $result = $stmt->fetchAll();

    return $result ? $result : false;
}

and the query

$home_team = query('SELECT home_team FROM premier_league
                    WHERE match_date >= :current_date
                    AND pre_selected = :pre_selected
                    ORDER BY match_date LIMIT 5',
                    array('current_date' => $current_date,
                    'pre_selected' =>$pre_selected),
                    $conn);
if (empty($home_team)){
    echo "No Match Selected for Today.";
} else {
    print_r($home_team);
}

How and where I use while loop for this query?

you don't need no while here

function query($query, $bindings, $conn) {
    $stmt = $conn->prepare($query);
    $stmt-> execute($bindings);
    return $stmt->fetchAll();
}
$sql = 'SELECT home_team FROM premier_league WHERE match_date >= ?
            AND pre_selected = ? ORDER BY match_date LIMIT 5';
$home_team = query($sql,array($current_date, $pre_selected), $conn);
foreach ($home_team as $row) {
    echo $row['home_team']."<br>
";
}

In else block

else {
    print_r($home_team);
    /* here
    foreach ($home_team as $team) {
       echo $team->home_team . '<br>';
    }*/
}

The idea of using a prepared query is to have the server parse the query once and create a query plan once. This is useful for queries that you execute repeatedly, only changing the parameter values. Accordingly: - the prepare should be done once. - the execute should be done inside the loop.

If you are executing a query once in a while, then the prepare overhead is not worth it.

PDOStatement implements Traversable so using fetchAll would be a overhead.

function query($query, $bindings, $conn) {
    $stmt = $conn->prepare($query);
    $stmt->execute($bindings);
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    return $stmt;        
}

$home_team = query...;
foreach ($home_team as $row) {
    echo $row['home_team']."<br>
";
}