2012-02-16 8 views
5

He creado un formulario donde el usuario puede buscar en la base de datos, y el resultado depende de cómo el usuario rellene el formulario.
Por ejemplo, supongamos que tengo nombre, dirección, ciudad, estado y campo zip, y el usuario rellena los campos de nombre y ciudad, los resultados reflejan la entrada. Cuando el formulario envía, se muestran todos los registros. para este escribo esto:Buscar base de datos MySQL con múltiples campos en un formulario

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 />"; 
      } 
     } 
    ?> 

Pero en este caso, un usuario puede dejar un campo en blanco.

+0

La codificación aquí no es segura contra los usuarios maliciosos. Lea http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php. –

Respuesta

12

Prueba esto:

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

Sí. ¡Está bien! –

+0

La codificación aquí no es segura contra usuarios maliciosos. Lea http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php. –

+1

Veo que esta respuesta está marcada como la mejor y más actualizada, pero ¿no debería $ _POST ['field'] ser $ _POST [$ field] en la línea 9? No quiero editar, ya que no soy un experto en php-er seguro, o sé por qué está escrito como lo hizo. Funciona para mí ahora que lo cambié, pero he abierto un agujero de seguridad (la entrada de entrada se ha desinfectado). – digitaltoast

Cuestiones relacionadas