0

我是 PHP 准备方法的新手,我需要一些帮助才能在以下代码中使用 while 循环。

这是查询功能

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

    return $result ? $result : false;
}

和查询

$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);
}

我如何以及在何处使用 while 循环进行此查询?

4

4 回答 4

0

PDOStatement实现Traversable因此使用fetchAll将是开销。

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>\n";
}
于 2013-07-07T11:39:15.863 回答
0

else

else {
    print_r($home_team);
    /* here
    foreach ($home_team as $team) {
       echo $team->home_team . '<br>';
    }*/
}
于 2013-07-07T11:25:10.587 回答
0

你不需要在这里

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>\n";
}
于 2013-07-07T11:31:21.097 回答
-1

使用准备好的查询的想法是让服务器解析一次查询并创建一次查询计划。这对于您重复执行的查询很有用,只更改参数值。因此: - 准备工作应该做一次。- 执行应该在循环内完成。

如果您偶尔执行一次查询,那么准备开销是不值得的。

于 2013-07-07T11:31:55.567 回答