我想为我的网站设置搜索textbox
和checkbox
过滤器。搜索将在checkbox
过滤活动时搜索地点和位置的名称。
现在我有一个有效的搜索textbox
和一个有效的checkbox
过滤器,但无法找出如何将它们组合。
我真的非常感谢任何帮助或链接到教程等,因为我还在学习这两种语言,并且最近才开始挣扎,现在我已经完全停顿了。
这是PHP
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("host", "dbo560757688", "pw") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("db560757688");
// Fruits
$fruits = array();
foreach($_POST['fruit'] as $fruit) {
$fruit = mysql_real_escape_string($fruit);
$fruits[] = "'{$fruit}'";
}
//-query the database table
$sql="SELECT * FROM Contacts WHERE Activity IN (" . implode(", ", $fruits) . ") AND FirstName LIKE '%" . $name . "%' OR LastName LIKE '%" . $name ."%'";
//-run the query against the mysql query function
?>
<?php
//omitted code
$result=mysql_query($sql);
//close your php just after this
}
}
}
?>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Activity</th>
</tr>
</thead>
<tbody>
<?php
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)):
$FirstName=$row['FirstName'];
$LastName=$row['LastName'];
$Activity=$row['Activity'];
$Email=$row['Email'];
//-display the result of the array
?>
<tr>
<td><?php echo $FirstName ?></td>
<td><?php echo $LastName?></td>
<td><?php echo $Activity ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
HTML CODE
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="name">
<br />
<input type="checkbox" name="fruit[]" value="Paintball" />
Banana<br />
<input type="checkbox" name="fruit[]" value="Swimming Pool" /> Apple
<br />
<input type="checkbox" name="fruit[]" value="Gym" /> Peach
<br />
<input type="submit" name="submit" value="Search">
</form>
</form>
答案 0 :(得分:0)
您使用php打印的html代码存在一些问题,例如,table
标记是未关闭的,与第一个tr
相同,而且,您拥有的所有代码都是for ,那么,它会被印刷得更多一次,是你想要的吗?
首先,我建议您尝试在$fruits[] = "'{$fruit}'";
之后关闭for循环,然后再试一次
修改强>
我认为你的SQL查询错了,改变
WHERE Activity LIKE (" . implode(", ", $fruits) . ")";
有:
WHERE Activity IN (" . implode(", ", $fruits) . ")";
您不能将LIKE
与逗号分隔的值一起使用,而是使用IN
你可以在同一个文件中混合使用html和php代码,这样你就可以做出像这样的事情
<?php
//...omitted code
$result=mysql_query($sql);
//close your php just after this
?>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Activity </th>
</tr>
</thead>
<tbody>
<?php
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)):
$FirstName=$row['FirstName'];
$LastName=$row['LastName'];
$Activity=$row['Activity'];
$Email=$row['Email'];
//-display the result of the array
?>
<tr>
<td><?php echo $FirstName ?></td>
<td><?php echo $LastName ?></td>
<td><?php echo $Activity ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>