简体   繁体   中英

php mysql multiple field search empty fields

<?php
if(isset($_POST['submit'])) {
    $fields = array('field1', 'field2', 'field3');
    $conditions = array();
    foreach($fields as $field){
        if(isset($_POST[$field]) && $_POST[$field] != '') {
            $conditions[] = "`".$field."` like '%" . mysql_real_escape_string($_POST[$field]) . "%'";
        }
    }
    $query = "SELECT * FROM customer ";
    if(count($conditions) > 0) {
        $query .= "WHERE " . implode (' AND ', $conditions); 
    }
    $result = mysql_query($query); 
    $say = mysql_num_rows($result);
    if ($say == 0) {
        echo "<tr>no result.</tr>";
        } else {

echo '...';     
    while($row = mysql_fetch_array($result))
  {
  ...

  }}
} ?>

Why doesn't this code checking empty fields? It returns results that has empty field even form submits empty.

The only improvement I think of is trim() :

if(isset($_POST[$field]) && trim($_POST[$field]) != '') {

however, I am sure it is not the issue.
Have you ever thought of printing the resulting query out ?
Look, you're writing a program to create some string (SQL query). But for some reason never interested in this program's direct result, judging it by some indirect results. May be it's data/query logic makes such results, but the query itself is okay?

if the query is still wrong - continue debugging.
Echo everything involved - print variables, condition results, intermediate results in the loop - and look for inconsistencies

$query = "SELECT * FROM customer ";
if(count($conditions) > 0) {
$query .= "WHERE " . implode (' AND ', $conditions); 
}

When form is submitted empty ($conditions=0) it returns all table (select * from customer).

Added an else condition and fixed. Thanks for print query advices.

For checking something is empty or not. You can use empty() method.

Check this:

empty()

isset() only check whether that object/variable is set or not. For more details check this

isset()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM