我是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循环的方式和位置?
答案 0 :(得分:0)
在else
区块
else {
print_r($home_team);
/* here
foreach ($home_team as $team) {
echo $team->home_team . '<br>';
}*/
}
答案 1 :(得分: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";
}
答案 2 :(得分: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";
}
答案 3 :(得分:-1)
使用准备好的查询的想法是让服务器解析一次查询并创建一次查询计划。这对于重复执行的查询非常有用,只会更改参数值。 因此: - 准备工作应该做一次。 - 执行应该在循环内完成。
如果您偶尔执行一次查询,则准备开销不值得。