我怀疑是数组错误或 mysql 查询错误。我已经打印了函数中的所有变量,它们返回了正确的结果,并在返回正确结果的 phpmyadmim 中尝试了相同的查询。
用例非常简单
- 获取
$_GET['gameID']
并查询数据库
- 从第一次查询中获取返回结果,并使用周数和运动第二次查询数据库。
- 返回一个包含第二次查询所有结果的数组
问题
当前函数只返回表的最后一行,而不是返回所有行。
表格图片
输出结果
代码
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
我是一名优秀的程序员,十分优秀!