如何避免mysql查询中的inlike语句为空

nom7f22z  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(334)

在我下面的代码中,我一直在从数据库中查询姓名和电子邮件,在本例中,如果姓名或电子邮件为空,它将获取所有数据。
如何避免这种情况?请帮忙
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 
}
?>
yx2lnoni

yx2lnoni1#

在不同的条件下写不同的语句怎么样

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
}
ca1c2owp

ca1c2owp2#

只要加上这个条件,检查它是否是空的

// 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   
    }
}

相关问题