我有一个包含5列的表格:ID,姓名,电子邮件,评论&约会时间。我创建了一个搜索表单,让用户通过姓名或电子邮件搜索记录。
这是我的代码:
<?php
// database info
$host = "localhost";
$username = "root";
$password = "root";
$db_name = "test";
$tbl_name = "abctable";
// conntect to server and select database
mysql_connect("$host", "$username", "$password") or die ("cannot connect server");
mysql_select_db("$db_name") or die ("cannot select DB");
// get data from search form
$name=$_POST['name'];
$email=$_POST['email'];
// if name & email is not empty, do this
if ((!empty($name)) || (!empty($email))) {
if(isset($_REQUEST['submit'])){
$sql=" SELECT * FROM $tbl_name WHERE name like '%".$name."%' OR email ='".$email."' ";
$q=mysql_query($sql);
}
else{
$sql="SELECT * FROM $tbl_name";
$q=mysql_query($sql);
}
}
else{
echo "Please type something in the search box below:<br><br>";
}
?>
<!-- Search Form -->
<form method="post" action="search.php">
<table width="200" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="name" /></td>
<td>Email</td>
<td><input type="text" name="email" /></td>
<td><input type="submit" name="submit" value=" Find " /></td>
</tr>
</table>
</form>
<?php
// Show this Result Table when Search Form is not empty
if ((!empty($name)) || (!empty($email))) { ?>
<!-- Result Table -->
<table border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Comment</td>
<td>Date & Time</td>
</tr>
<?php while($res=mysql_fetch_array($q)){ ?>
<tr>
<td><?php echo $res['id'];?></td>
<td><?php echo $res['name'];?></td>
<td><?php echo $res['email'];?></td>
<td><?php echo $res['comment'];?></td>
<td><?php echo $res['datetime'];?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
<?php mysql_close(); // close database ?>
我遇到了电子邮件搜索SQL的问题。该名称正在运行并成功返回正确的记录。如何解决这个问题?
答案 0 :(得分:0)
可能会将查询更改为
$sql="SELECT * FROM $tbl_name
WHERE (".$name." <> '' and name like '%".$name."%')
OR (".$email." <> '' and email like '%".$email."%')."' ";
如果变量为空,这将排除该变量。
答案 1 :(得分:0)
保持清洁这样做:
if(isset($_REQUEST['submit']))
{
$sql=" SELECT * FROM $tbl_name WHERE name like $name OR email like $email
$q=mysql_query($sql);
}else
{
echo "Please type something in the search box below:<br><br>";
}
我相信你做的事情会更好。我有一个登录脚本,如果以上操作不起作用,我会检查并发布。