在下面的代码中,我一直在从数据库中查询姓名和电子邮件, 在这种情况下,如果名称或电子邮件为空,它将获取所有数据。
如何避免这种情况?请帮助
MySQL查询:
$searchdata = mysqli_query($this->dbh, "SELECT insertdata.name, insertdata.email, state.StateName, district.DistrictName
FROM insertdata
INNER JOIN state ON insertdata.state = state.StCode
INNER JOIN district ON insertdata.district = district.DistCode
WHERE name LIKE '%$namesearch%' OR email LIKE '%$emailsearch%'");
我的代码,
<?php
include_once("function.php");
$searchdata=new DB_con();
if(isset($_POST['submit']))
{
$namesearch=$_POST['namesearch'];
$emailsearch=$_POST['emailsearch'];
}
$search=$searchdata->searchdata($namesearch,$emailsearch);
foreach($search as $search)
{
?>
<tr>
<td><?php echo ($search['name']);?></td>
<td><?php echo ($search['email']);?></td>
<td><?php echo ($search['StateName']);?></td>
<td><?php echo ($search['DistrictName']);?></td>
</tr>
<?php
}
?>
答案 0 :(得分:0)
如果条件要检查天气是否为空,则只需添加
// check here
if ($namesearch == '' || $emailsearch =='')
{
echo 'Please enter name or email to search.';
} else {
$search = $searchdata->searchdata($namesearch,$emailsearch);
foreach($search as $search)
{
?>
<tr>
<td><?php echo ($search['name']); ?></td>
<td><?php echo ($search['email']); ?></td>
<td><?php echo ($search['StateName']); ?></td>
<td><?php echo ($search['DistrictName']); ?></td>
</tr>
<?php
}
}
答案 1 :(得分:0)
如何针对各种条件编写不同的语句
if($namesearch == '' && $emailsearch !=''){
$searchdata = mysqli_query($this->dbh, "SELECT insertdata.name, insertdata.email, state.StateName, district.DistrictName
FROM insertdata INNER JOIN state ON insertdata.state = state.StCode INNER JOIN district ON insertdata.district
= district.DistCode WHERE email LIKE '%$emailsearch%'");
}
else if($namesearch != '' && $emailsearch ==''){
$searchdata = mysqli_query($this->dbh, "SELECT insertdata.name, insertdata.email, state.StateName, district.DistrictName
FROM insertdata INNER JOIN state ON insertdata.state = state.StCode INNER JOIN district ON insertdata.district
= district.DistCode WHERE name LIKE '%$namesearch%'");
}
else if{
//bla bla bla
}