只要我从Story类别中选择至少一个复选框,这就有效。如果没有选中Story的复选框,我检查任何其他类别,则不返回任何内容。
我真的很想知道是什么造成了这么奇怪的错误。
homes数据库按此顺序排列: 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>
答案 0 :(得分:1)
您的代码是正确的,因为您首先检查:
if (isset($_POST['story'])) {
您可以添加其他复选框,例如:
if (isset($_POST['story']) || isset($_POST['bedroom']) || isset($_POST['bath']) {
这取决于你的目标。