Home:ALL Converter>php mysql multiple field search empty fields

php mysql multiple field search empty fields

Ask Time:2013-02-14T16:56:47         Author:milesh

Json Formatter

<?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.

Author:milesh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/14871026/php-mysql-multiple-field-search-empty-fields
Your Common Sense :

The only improvement I think of is trim():\n\nif(isset($_POST[$field]) && trim($_POST[$field]) != '') {\n\n\nhowever, I am sure it is not the issue.\nHave you ever thought of printing the resulting query out?\nLook, 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?\n\nif the query is still wrong - continue debugging.\nEcho everything involved - print variables, condition results, intermediate results in the loop - and look for inconsistencies ",
2013-02-14T09:28:28
milesh :

$query = \"SELECT * FROM customer \";\nif(count($conditions) > 0) {\n$query .= \"WHERE \" . implode (' AND ', $conditions); \n}\n\n\nWhen form is submitted empty ($conditions=0) it returns all table (select * from customer).\n\nAdded an else condition and fixed. Thanks for print query advices.",
2013-02-14T09:39:00
yy