php&mysql:为什么mysql不能读取!空的?

3lxsmp7m  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(251)

我尝试在数据库中搜索多个字段,用户也可以只搜索一个输入。但是现在,问题是sql不想读取(!空)在if-else条件下(如果我只想搜索1个输入)。但是如果我填充所有的搜索字段,它会显示得很好。如果我做错了,请改正。全面质量管理!
所以,这是我的代码:

if(!empty($_POST['search4']))
{
    $tarikh = $_POST['tahun'];
$tempat= $_POST['tempat'];
$sesi = $_POST['sesi'];
$status = $_POST['status'];
echo $tarikh;
echo $tempat;

    $field = array($tarikh,$tempat,$sesi,$status);
    $conditions = array();

foreach($field as $fields)
{
    if(isset($_POST[$fields]))
    {

        $conditions[] = "'$fields' LIKE '%".mysql_real_escape_string($_POST[$fields])."%'";

    }
}
$query = "SELECT * FROM tempahanbilik WHERE status!='BELUM DIPROSES' AND kosong = 'tidak' AND MONTH(tarikh) = 5 AND YEAR(tarikh) = YEAR(CURDATE()) AND YEAR(tarikh2) = YEAR(CURDATE()) ";
            if(count($conditions>0))
            {
                $query .="WHERE" .implode('OR',$conditions);
            }

$result = $mysqli->query($query) or die($mysqli->error._LINE_);

        $total = $result->num_rows;

        if($total>0)
        {
            $total =1;
        while($row = $result->fetch_assoc())
        {       
                $kp = $row['PenggunanoKP'];
                        $a = "SELECT * FROM pengguna WHERE PenggunanoKP = '$kp'";
                        $results = $mysqli->query($a) or die($mysqli->error._LINE_);
                     $rows = $results->fetch_assoc();

                //display the informations
        }               
    } 
    else
    {   
        echo"  
        <tr>
          <td>-</td>
          <td>-</td>
          <td>-</td>
          <td>-</td>
          <td>-</td>
          <td>-</td> 
          <td>-</td>
          <td>-</td>
          <td>-</td> 
          <td>-</td>
        </tr>\n";        
    }

错误显示:

Notice: Use of undefined constant _LINE_ - assumed '_LINE_' in C:\xampp\htdocs\booking\search.php on line 106
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE' at line 1_LINE_
3qpi33ja

3qpi33ja1#

您需要省略if条件的其他部分,因为您已经在使用 !empty 由此:

if($tarikh && !empty($tarikh))
{
    $query .="AND YEAR(tarikh) = $tarikh AND YEAR(tarikh2) = $tarikh";
}
if($tempat && !empty($tempat))
{
    $query .="AND  tempat = '$tempat'";
}
if($sesi && !empty($sesi))
{
    $query .="AND masa = '$sesi'";
}
if($status && !empty($status))
{
    $query .="AND status = '$status'";
}

对此:

if(!empty($tarikh))
{
    $query .=" AND YEAR(tarikh) = $tarikh AND YEAR(tarikh2) = $tarikh ";
}
if(!empty($tempat))
{
    $query .=" AND  tempat = '$tempat' ";
}
if(!empty($sesi))
{
    $query .=" AND masa = '$sesi' ";
}
if(!empty($status))
{
    $query .=" AND status = '$status' ";
}

在前面加上一些空格 AND 否则,您的查询将如下所示:

AND YEAR(tarikh) = $tarikh AND YEAR(tarikh2) = $tarikhAND  tempat = '$tempat'AND masa = '$sesi'

当这些变量用当前值更改时,将返回一个错误。

相关问题