只要我从“故事”类别中选择至少一个复选框,这就会起作用。如果没有选中 Story 中的复选框并且我检查了任何其他类别,则不会返回任何内容。
我真的很想知道是什么导致了如此奇怪的错误。
家庭数据库按以下顺序排列:homes_id 姓名 故事 卧室 浴室
编辑:我之前问过这个问题的前一部分,但现在我正在处理另一个障碍编辑:忘记将 $valid_responses 添加到 foreach
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Homes Test 2</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<h3>story</h3>
<label><input type="checkbox" name="story[]" value="1" id="story_1" />one story</label>
<label><input type="checkbox" name="story[]" value="2" id="story_2" />two story</label>
</p>
<p>
<h3>bedrooms</h3>
<label><input type="checkbox" name="bedroom[]" value="2" id="bed_2" />two beds</label>
<label><input type="checkbox" name="bedroom[]" value="3" id="bed_3" />three beds</label>
<label><input type="checkbox" name="bedroom[]" value="4" id="bed_4" />four beds</label>
</p>
<p>
<h3>baths</h3>
<label><input type="checkbox" name="bath[]" value="1" id="bath_1" />one bath</label>
<label><input type="checkbox" name="bath[]" value="2" id="bath_2" />two baths</label>
<label><input type="checkbox" name="bath[]" value="3" id="bath_3" />three baths</label>
</p>
<input type="submit" value="search" />
</form>
<?php
if (isset($_POST['story'])) {
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'testpass');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'homes');
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
$q = "SELECT name, story, bedroom, bath FROM homes WHERE 1";
// Protect against injection attacks
$valid_responses = array(
'bedroom' => array(
'1','2'),
'story' => array(
'1','2'),
'bath' => array(
'1','2','3'),
);
foreach ($valid_responses as $field=>$values) {
$selection = array_intersect($_POST[$field],$values);
if (!empty($selection)) {
$q .= ' AND ' . $field . ' IN ("' . implode('", "', $selection) . '")';
$r = mysqli_query($dbc, $q);
}else{
echo "selection was empty";
}
}
while($data = $r->fetch_assoc()) {
$rows[] = $data;
}
echo json_encode($rows);
echo "<pre>$q</pre>";
}
?>
</body>
</html>