我有以下代码,它应该返回某个区域内的所有团队。我有一个足球队数据库,其中包含球队和国家队的表格。 teams表具有状态表的外键引用,states表具有区域(北,南,东,西)的属性。
我的主页上有以下html / php代码:
<div>
<form method="post" action="regions_filter.php">
<fieldset>
<legend>Filter Teams By Region</legend>
<select name="Region">
<?php
if(!($stmt = $mysqli->prepare("SELECT DISTINCT region FROM states"))){
echo "Prepare failed: " . $stmt->errno . " " . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
if(!$stmt->bind_result($region)){
echo "Bind failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
while($stmt->fetch()){
echo '<option value=" ' . $region . ' "> ' . $region . '</option>\n';
}
$stmt->close();
?>
</select>
<input type="submit" value="Run Filter"/>
</fieldset>
</form>
</div>
下面是regions_filter.php文件代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<body>
<div>
<table>
<tr>
<td>Teams By Region</td>
</tr>
<tr>
<td>School Name</td>
<td>State Name</td>
<td>State Capital</td>
<td>State Population</td>
<td>Region</td>
</tr>
<?php
if(!($stmt = $mysqli->prepare("SELECT teams.school_name, states.name, states.capital, states.population, states.region FROM teams
INNER JOIN states ON states.id = teams.state_id
WHERE states.region = ?"))){
echo "Prepare failed: " . $stmt->errno . " " . $stmt->error;
}
if(!($stmt->bind_param("s",$_POST['Region']))){
echo "Bind failed: " . $stmt->errno . " " . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: " . $mysqli->connect_errno . " " . $mysqli- >connect_error;
}
if(!$stmt->bind_result($school, $state, $capital, $population, $region)){
echo "Bind failed: " . $mysqli->connect_errno . " " . $mysqli- >connect_error;
}
while($stmt->fetch()){
echo "<tr>\n<td>" . $school . "\n</td>\n<td>" . $state . "\n</td>\n<td>" . $capital . "\n</td>\n</td>"
. $population . "\n</td>\n<td>" . $region . "\n</td>\n</tr>";
}
$stmt->close();
?>
</table>
</div>
</body>
</html>
当我在主页面上运行过滤器时,我被带到regions_filter.php页面,但没有结果。唯一显示的是regions_filter.php页面顶部的预编码html表。 我相信错误发生在下面的代码段中。我已尝试使用选项值进行不同的变化,但似乎无法破解它:
while($stmt->fetch()){
echo '<option value=" ' . $region . ' "> ' . $region . '</option>\n';
}
任何指向正确方向的人都会非常感激。
答案 0 :(得分:0)
我相信你的where语句中的states.id不是region id。如果要将$ region作为参数从标记过滤到select语句state.id =? (state.id = $ region)它不会给出任何结果。因为你是通过状态过滤的。 注意:这只是我对上述代码的第一次理解
我认为你没有任何错误......只是你可能会过滤错误的属性^ _ ^
答案 1 :(得分:0)
填充区域时出现错误选择区域名称前后有一个额外的空白区域。应该是这样的:
while($stmt->fetch()){
echo '<option value="' . $region . '">' . $region . '</option>\n';
}