我试图将$ row []值分配给变量,以便我可以在表单中使用它。由于我两次加入表,因此2列具有相同的名称。我试图使用如图所示的别名来分配变量,但它们返回null(可能是语法错误?)。查询检查正常
<?php
//This will list player info so the user can get the correct player ID
$STH = $db->query('
SELECT wW.id, wW.dateStart, wW.dateEnd, wW.weekNumber, wW.team1Id, wW.team2Id, wT1.name, wT2.name
FROM wdlWeeks wW
JOIN wdlTeams wT1 on wT1.id = wW.team1Id
JOIN wdlTeams wT2 on wT2.id = wW.team2Id
');
//Setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
//Output all players with their ID's
while($row = $STH->fetch()) {
$id = $row['wW.id'];
$team1Name = $row['wT1.name'];
$team2Name = $row['wT2.name'];
$dateStart = $row['wW.dateStart'];
$dateEnd = $row['wW.dateEnd'];
$weekNumber = $row['wW.weekNumber'];
echo "<option value='$id'>$team1Name vs. $team2Name (Week: $weekNumber - $dateStart - $dateEnd)</option>";
echo "<br>";
}
?>
答案 0 :(得分:0)
您不需要每个变量前面的wW.
等,这些列将仅作为其名称返回
另外,由于您有2个具有相同名称的列,因此您必须修改查询,以便为其中一个name
列添加另一个名称
$STH = $db->query('
SELECT wW.id, wW.dateStart, wW.dateEnd, wW.weekNumber,
wW.team1Id, wW.team2Id, wT1.name, wT2.name as t2name
FROM wdlWeeks wW
JOIN wdlTeams wT1 on wT1.id = wW.team1Id
JOIN wdlTeams wT2 on wT2.id = wW.team2Id
');
//Setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
//Output all players with their ID's
while($row = $STH->fetch()) {
$id = $row['id'];
$team1Name = $row['name'];
$team2Name = $row['t2name'];
$dateStart = $row['dateStart'];
$dateEnd = $row['dateEnd'];
$weekNumber = $row['weekNumber'];
echo "<option value='$id'>$team1Name vs. $team2Name (Week: $weekNumber - $dateStart - $dateEnd)</option>";
echo "<br>";
}
答案 1 :(得分:0)
您可以为每个字段使用别名:
SELECT wW.id,wW.dateStart,wW.dateEnd,wW.weekNumber,wW.team1Id,wW.team2Id, wT1.name AS Team1Name,wT2.name AS Team2Name 来自wdlWeeks wW 在wT1.id = wW.team1Id上加入wdlTeams wT1 在wT2.id = wW.team2Id
上加入wdlTeams wT2然后:
$ team1Name = $ row ['Team1Name']
答案 2 :(得分:0)
别名是默认的列名,因此您使用&#39; name&#39;有两列,并且根本不包含表别名。例如,在查询中使用AS wT1name
,然后将这些字符串用于从$ row中提取的别名。像这样:
<?php
//This will list player info so the user can get the correct player ID
$STH = $db->query('
SELECT wW.id, wW.dateStart, wW.dateEnd, wW.weekNumber, wW.team1Id, wW.team2Id, wT1.name AS wT1name, wT2.name AS wT2name
FROM wdlWeeks wW
JOIN wdlTeams wT1 on wT1.id = wW.team1Id
JOIN wdlTeams wT2 on wT2.id = wW.team2Id
');
//Setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
//Output all players with their ID's
while($row = $STH->fetch()) {
$id = $row['id'];
$team1Name = $row['wT1name'];
$team2Name = $row['wT2name'];
$dateStart = $row['dateStart'];
$dateEnd = $row['dateEnd'];
$weekNumber = $row['weekNumber'];
echo "<option value='$id'>$team1Name vs. $team2Name (Week: $weekNumber - $dateStart - $dateEnd)</option>";
echo "<br>";
}
?>