gpt4 book ai didi

遍历 foreach 循环的 PHP 数组或 SQL 错误

转载 作者:太空宇宙 更新时间:2023-11-03 10:36:04 24 4
gpt4 key购买 nike

我怀疑是数组错误或 mysql 查询错误。我已经打印了函数中的所有变量,它们返回了正确的结果,并在返回正确结果的 phpmyadmim 中尝试了相同的查询。

用例非常简单

  1. 获取$_GET['gameID']并查询数据库
  2. 从第一次查询中获取返回结果,并使用周数和运动第二次查询数据库。
  3. 返回一个包含第二次查询所有结果的数组

问题

当前函数只返回表的最后一行,而不是返回所有行。

表格图片

enter image description here输出结果

enter image description here

代码

function displayTeamsByGameID($gameID)
{
global $db;
//now prevents late submissions
$sql = "SELECT * FROM bru_schedule WHERE gameID = :gameID";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':gameID', $gameID);
$stmnt->execute();
if ($stmnt->rowCount() > 0) {
$games = $stmnt->fetch();
print $weekNum = $games['weekNum'];
print $sport = $games['sport'];
$sql = "SELECT * FROM bru_schedule WHERE weekNum = :weekNum AND sport = :sport";
$stmnt= $db->prepare($sql);
$stmnt->bindValue(':weekNum', $weekNum);
$stmnt->bindValue(':sport', $sport);
$stmnt->execute();
if($stmnt->rowCount() > 0){
$matches= $stmnt->fetchAll();
foreach ($matches as $match) {
$match[] = array('gameID' => $match['gameID'], 'weekNum' => $match['weekNum'], 'gameTimeEastern' => $match['gameTimeEastern'], 'homeID' => $match['homeID'], 'visitorID' => $match['visitorID'], 'sport' => $match['sport'], 'venue' => $match['venue'], 'tournament' => $match['tournament'], 'spread' => $match['spread']);

}//foreach
}//statment weekNUm Sport
}//statment gameID
if (!isset($match)) {
return false;
}
return $match;
}//function

如果有人可以快速浏览我的代码或提供一些建议,我们将不胜感激。

最佳答案

您正在覆盖 $match 变量,因为您在 foreach 语句和 foreach 主体中使用了相同的变量来创建结果数组。使用不同的变量。请参阅下面的代码。我为结果使用了一个新变量 $result

function displayTeamsByGameID($gameID)
{
global $db;
//now prevents late submissions
$sql = "SELECT * FROM bru_schedule WHERE gameID = :gameID";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':gameID', $gameID);
$stmnt->execute();
if ($stmnt->rowCount() > 0) {
$result = array();
$games = $stmnt->fetch();
print $weekNum = $games['weekNum'];
print $sport = $games['sport'];
$sql = "SELECT * FROM bru_schedule WHERE weekNum = :weekNum AND sport = :sport";
$stmnt= $db->prepare($sql);
$stmnt->bindValue(':weekNum', $weekNum);
$stmnt->bindValue(':sport', $sport);
$stmnt->execute();
if($stmnt->rowCount() > 0){
$matches= $stmnt->fetchAll();
foreach ($matches as $match) {
$result[] = array('gameID' => $match['gameID'], 'weekNum' => $match['weekNum'], 'gameTimeEastern' => $match['gameTimeEastern'], 'homeID' => $match['homeID'], 'visitorID' => $match['visitorID'], 'sport' => $match['sport'], 'venue' => $match['venue'], 'tournament' => $match['tournament'], 'spread' => $match['spread']);

}//foreach
}//statment weekNUm Sport
}//statment gameID
if (!isset($result)) {
return false;
}
return $result;
}//function

关于遍历 foreach 循环的 PHP 数组或 SQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48143794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com