我有一个由数据库填充的droplist。我正在尝试获取与其表ID相关的数据。我可以获取数据,但它返回所有数据而不是特定于运动的ID。当我从下拉列表中选择一项运动时,请点击我想要返回该数据的按钮。
我有两个文件,一个是动作,另一个文件是下拉列表
<form method='POST' action="sportSearch.php">
<fieldset>
<div id="dropDownList">
<select value="sport" name="sport">
<?php
try {
$dropDownSport = $pdo->prepare('SELECT sportName FROM sport');
$dropDownSport->execute();
$dropDown = $dropDownSport->fetchAll();
} catch(PDOException $e) {
$error = 'Select statement error';
include 'error.html.php';
exit();
}
foreach($dropDown as $row) {
echo'<option value='.$row["sportID"].'>'.$row["sportName"].'</option>';
}
?>
</select>
</div>
<div>
<button type="submit">Submit</button>
</div>
</fieldset>
</form>
下面我试图找到特定运动的id,但它只是输出
$sportId = $_POST['sport'];
$where = "";
$search_sport_id = false;
if(is_numeric($sportId)) {
$search_sport_id = true;
$where = "WHERE sport.sportID = :sportID";
}
try {
$selectSport = $pdo->prepare ('SELECT athlete.athleteID,
athlete.eventID, athlete.sportID, athlete.lastName, athlete.firstName,
athlete.gender, event.eventName, sport.sportName, athlete.gender,
athlete.image, athlete.medal
FROM athlete JOIN event ON event.eventID = athlete.eventID JOIN sport
ON sport.sportID = athlete.sportID '.$where);
if($search_sport_id == true) {
$selectSport->execute(array(':sportID' => $sportId));
} else {
$selectSport->execute();
}
} catch(PDOException $e) {
$error = 'Select statement error';
include 'error.html.php';
exit();
}
然后输出到表
<table>
<tr>
<th>athleteID</th>
<th>eventID</th>
<th>sportID</th>
<th>lastName</th>
<th>firstName</th>
<th>eventName</th>
<th>sportName</th>
<th>gender</th>
<th>image</th>
<th>medal</th>
</tr>
<?php
if(!empty($selectSport)) {
foreach($selectSport as $row) {
echo'<tr>';
echo'<td>'.$row['athleteID'].'</td>';
echo'<td>'.$row['eventID'].'</td>';
echo'<td>'.$row['sportID'].'</td>';
echo'<td>'.$row['lastName'].'</td>';
echo'<td>'.$row['firstName'].'</td>';
echo'<td>'.$row['eventName'].'</td>';
echo'<td>'.$row['sportName'].'</td>';
echo'<td>'.$row['gender'].'</td>';
echo'<td><img src="photos/'.$row['image'].'"</td>';
echo'<td>'.$row['medal'].'</td>';
echo'</tr>';
}
}
?>
</table>
答案 0 :(得分:0)
您的问题是$row['sportID']
不存在。
让我们看看你的查询:
$dropDownSport = $pdo->prepare('SELECT sportName FROM sport');
您只选择&#39; sportName&#39;从表中。你想要的是:
$dropDownSport = $pdo->prepare('SELECT sportID, sportName FROM sport');
我想指出的另外两件事:
在PHP中调试
在PHP中进行调试可能非常简单,特别是在这种情况下。您应该做的是在第二个脚本中$sportId
之后回显$sportId = $_POST['sport'];
- 这会向您显示这是一个空变量。或者您可以在下拉列表中使用浏览器检查功能 - 它会向您显示值为空。
面向对象的PHP
我最讨厌的PHP之一是避免使用对象的人。我发现它们在数据库方面特别有用。看看 - 它确实可以帮助您解决未来的问题(IMO面向对象的PHP更容易调试)。