2012-02-16 82 views
5

我已经创建了一个用户可以搜索数据库的表单,结果取决于用户如何填写表单。
例如,假设我有姓名,地址,城市,州和邮编字段,并且用户填写姓名和城市字段,则结果反映输入。当表单提交时,所有记录都显示出来。 为了这个,我这样写:以表单中的多个字段搜索MySQL数据库

if(isset($_POST['submit'])) { 
     $sql = mysql_query("SELECT * FROM table WHERE name LIKE '%" . $_POST['name'] . "%' 
        OR address LIKE '%" . $_POST['address'] . "%' 
        OR city LIKE '%" . $_POST['city'] . "%' 
        OR state LIKE '%" . $_POST['state'] . "%' 
        OR zip LIKE '%" . $_POST['zip'] . "%'"); 
    } 


     <form method="post" action="<?php $_SERVER['PHP_SELF']; ?>"> 
      <tr> 
       <td>Name:</td> 
       <td><input type="text" name="name" /></td> 
      </tr> 
      <tr> 
       <td>Address:</td> 
       <td><input type="text" name="address" /></td> 
      </tr> 
      <tr> 
       <td>City:</td> 
       <td><input type="text" name="city" /></td> 
      </tr> 
      <tr> 
       <td>State:</td> 
       <td><input type="text" name="state" /></td> 
      </tr> 
      <tr> 
       <td>Zip:</td> 
       <td><input type="text" name="zip" /></td> 
      </tr> 
      <tr> 
       <td>&nbsp;</td> 
       <td><input type="submit" name="submit" value="Search" /></td> 
      </tr> 
     </form> 
    </table> 

    <?php 
     if(isset($_POST['submit'])) { 
      while($row = mysql_fetch_array($sql)) { 
       echo $row['name'] . "<br />"; 
      } 
     } 
    ?> 

但是,在这种情况下,用户可以将字段留空。

+0

这里的编码不是安全防范恶意用户。请阅读http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php。 – 2012-05-09 16:43:57

回答

12

试试这个:

if(isset($_POST['submit'])) { 
    // define the list of fields 
    $fields = array('name', 'address', 'city', 'state', 'zip'); 
    $conditions = array(); 

    // loop through the defined fields 
    foreach($fields as $field){ 
     // if the field is set and not empty 
     if(isset($_POST[$field]) && $_POST[$field] != '') { 
      // create a new condition while escaping the value inputed by the user (SQL Injection) 
      $conditions[] = "`$field` LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'"; 
     } 
    } 

    // builds the query 
    $query = "SELECT * FROM TABLE "; 
    // if there are conditions defined 
    if(count($conditions) > 0) { 
     // append the conditions 
     $query .= "WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative 
    } 

    $result = mysql_query($query); 
+0

是的。这是正确的方式! – 2012-02-16 19:47:16

+0

这里的编码对恶意用户不安全。请阅读http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php。 – 2012-05-09 16:44:47

+1

我看到这个答案被标记为最好的和被高估的,但不应该$ _POST ['field']是第9行的$ _POST [$ field]?我不想编辑,因为我不是一个足够熟练的php-er,或者知道它为什么被写入。它现在适用于我,现在我改变了它,但是我打开了一个安全漏洞(后输入已被消毒)。 – digitaltoast 2014-12-15 14:34:53

相关问题