• Viernes 29 de Marzo de 2024, 13:24

Autor Tema:  Problema Con Consulta  (Leído 1268 veces)

neorent

  • Miembro MUY activo
  • ***
  • Mensajes: 249
    • Ver Perfil
    • http://www.laestokada.cl
Problema Con Consulta
« en: Lunes 24 de Septiembre de 2007, 19:10 »
0
Estimado foreros:

   Mas que problema es una gran duda, resulta que tengo un formulario, el cual contiene 7 campos, distintos, pero que a la vez que estan relacionados,

necesito crear una consulta que me indique que si los campos que me envio el usuario vienen todos si no vienen todos, que realice una busqueda por los campos que envio el usuario, el problema es que no se como hacerlo, yo hice lo siguiente, pero es demasiado largo, ya que al menos tuve que crear como 100 tipos de consultas distintas, segun el campo, les dejo el code para que vean.

formulario.php

Código: Text
  1.  
  2. <?
  3. <form name="b_avanzada" action="b_patentes1.php" method="get" >
  4.   <table width="100%">
  5. <tr>
  6. <td colspan="2" ><div align="center">BÚSQUEDA PATENTES </div></td>
  7. </tr>
  8.   <tr>
  9.     <td width="252">TIPO PATENTE </td>
  10.     <td width="372" >
  11.       <label>
  12.         <select name="tipo_patente2" id="tipo_patente2">
  13.           <option value="ALL">SELECCIONE TIPO PATENTE...</option>
  14.           <option value="ALCOH">PATENTES ALCOHOL</option>
  15.           <option value="COMER">PATENTES COMERCIALES</option>
  16.           <option value="ESTAC">PATENTES DE ESTACIONAMIENTO</option>
  17.           <option value="FERIA">PATENTES DE FERIAS LIBRES</option>
  18.           <option value="INDUS">PATENTES INDUSTRIALES</option>
  19.           <option value="PROFE">PATENTES DE PROFESIONALES</option>
  20.           <option value="PROPA">PATENTES DE PROPAGANDA</option>
  21.         </select>
  22.       </label>
  23.       <label></label></td>
  24.   </tr>
  25.   <tr>
  26.     <td >VALOR PATENTE </td>
  27.     <td><label>DESDE
  28.       <input name="valor_patente_desde" type="text" id="valor_patente_desde" size="12">
  29.     </label>
  30.       HASTA
  31.       <label>
  32.       <input name="valor_patente_hasta" type="text" id="valor_patente_hasta" size="12">
  33.       </label></td>
  34.   </tr>
  35.   <tr>
  36.     <td>CAPITAL</td>
  37.     <td><span class="Estilo6">DESDE</span>
  38.       <input name="capital_desde" type="text" id="capital_desde" size="12" />
  39.       <span class="Estilo6">HASTA</span>
  40.       <input name="capital_hasta" type="text" id="capital_hasta" size="12" />
  41.       <label></label></td>
  42.   </tr>
  43.   <tr>
  44.     <td class="Estilo6">Nº TRABAJADORES </td>
  45.     <td><input name="n_trabajadores" type="text" id="n_trabajadores" size="12" />
  46.       <label></label></td>
  47.   </tr>
  48.   <tr>
  49.     <td class="Estilo6">SUCURSALES FUERA DE SANTIAGO </td>
  50.     <td><? sucursales()?></td>
  51.   </tr>
  52.   <tr>
  53.     <td colspan="2" class="Estilo6" align="center">
  54.       <label>
  55.       <input name="Submit" type="submit" class="Estilo6" value="Buscar" />
  56.       <input name="Limpiar" type="reset" class="Estilo6" id="Limpiar" value="Limpiar" />
  57.       <input name="Volver" type="button" class="Estilo6" id="Volver" value="Volver" onclick="volver()" />
  58.       <input name="antiguedad_desde" type="hidden" id="antiguedad_desde" value="" />
  59.       <input name="antiguedad_hasta" type="hidden" id="antiguedad_hasta" value="" />
  60.       </label></td>
  61.     </tr>
  62. </table>
  63. </form>
  64. <?
  65. function sucursales()
  66. {
  67.   $link = mysql_connect("localhost", "intranet", "intranet");
  68.   mysql_select_db("db_clt_municipales", $link);
  69.   $sql=mysql_query("SELECT COUNT( * ) AS Filas , tiene_s_f_stgo FROM patentes GROUP BY tiene_s_f_stgo ORDER BY tiene_s_f_stgo ASC");
  70.   // Voy imprimiendo el primer select compuesto por los paises
  71.   echo "<select name='sucursales' id='sucursales'>";
  72.   echo "<option value='ALL'>Sucursales...</option>";
  73.   while($registro=mysql_fetch_row($sql))
  74.   {
  75.     if ($registro[1]==NULL)
  76.     {
  77.     echo;
  78.     }
  79.     else
  80.     {
  81.     echo "<option value='".$registro[1]."'>".$registro[1]."</option>";
  82.     }
  83.   }
  84.   echo "</select>";
  85. }
  86. ?>
  87. <script>
  88. function volver()
  89. {
  90. setTimeout("<?php echo "location.href='menu.php'";?>", 1);
  91. }
  92. </script>
  93.  
  94.  

y este es donde hago la busqueda

b_patentes1.php

Código: Text
  1.  
  2. ////////////////////////////////////////////////////
  3. //Convierte fecha de mysql a normal
  4. ////////////////////////////////////////////////////
  5. function cambiaf_a_normal($fecha){
  6.     ereg( "([0-9]{2,4})-([0-9]{1,2})-([0-9]{1,2})", $fecha, $mifecha);
  7.     $lafecha=$mifecha[3]."/".$mifecha[2]."/".$mifecha[1];
  8.     return $lafecha;
  9. }
  10.  
  11. ////////////////////////////////////////////////////
  12. //Convierte fecha de normal a mysql
  13. ////////////////////////////////////////////////////
  14.  
  15. function cambiaf_a_mysql($fecha){
  16.     ereg( "([0-9]{1,2})/([0-9]{1,2})/([0-9]{2,4})", $fecha, $mifecha);
  17.     $lafecha=$mifecha[3]."-".$mifecha[2]."-".$mifecha[1];
  18.     return $lafecha;
  19. }
  20. $a="01"."/"."01"."/";
  21. $tipo_patente=$_GET['tipo_patente2'];
  22. $valor_patente_desde=$_GET['valor_patente_desde'];
  23. $valor_patente_hasta=$_GET['valor_patente_hasta'];
  24. $antiguedad_desde=$_GET['antiguedad_desde'];
  25. $antiguedad_hasta=$_GET['antiguedad_hasta'];
  26. $capital_desde=$_GET['capital_desde'];
  27. $capital_hasta=$_GET['capital_hasta'];
  28. $n_trabajadores=$_GET['n_trabajadores'];
  29. $sucursales=$_GET['sucursales'];
  30. $link = mysql_connect("localhost","intranet","intranet");
  31. mysql_select_db("db_clt_municipales",$link);
  32.  
  33. if (($tipo_patente=="ALL") and ($valor_patente_desde==NULL) and ($valor_patente_hasta==NULL) and ($antiguedad_desde==NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  34.   {
  35.   //echo "uno";
  36.   $sql="SELECT * FROM patentes ORDER BY n_patente ASC";
  37.   }
  38.  
  39. if(($tipo_patente<>"ALL")and ($valor_patente_desde==NULL) and ($valor_patente_hasta==NULL) and ($antiguedad_desde==NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  40.   {
  41.   //echo "dos";
  42.   $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' ORDER BY n_patente ASC";
  43.   }
  44.  
  45. if(($tipo_patente=="ALL")and ($valor_patente_desde<>NULL) and ($valor_patente_hasta==NULL) and ($antiguedad_desde==NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  46.   {
  47.   //echo "tres";
  48.   $sql="SELECT * FROM patentes WHERE   (valor >='$valor_patente_desde')  ORDER BY valor ASC";
  49.   }
  50.  
  51. if(($tipo_patente<>"ALL")and ($valor_patente_desde<>NULL) and ($valor_patente_hasta==NULL) and ($antiguedad_desde==NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  52.   {
  53.   //echo "cuatro";
  54.   $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' AND (valor >='$valor_patente_desde')  ORDER BY valor ASC";
  55.   }
  56.  
  57. if(($tipo_patente=="ALL")and ($valor_patente_desde==NULL) and ($valor_patente_hasta<>NULL) and ($antiguedad_desde==NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  58.   {
  59.   //echo "cinco";
  60.   $sql="SELECT * FROM patentes WHERE (valor <= '$valor_patente_hasta')  ORDER BY valor ASC";
  61.   }
  62.  
  63. if(($tipo_patente<>"ALL")and ($valor_patente_desde==NULL) and ($valor_patente_hasta<>NULL) and ($antiguedad_desde==NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  64.   {
  65.   //echo "seis";
  66.   $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' AND (valor <= '$valor_patente_hasta')  ORDER BY valor ASC";
  67.   }
  68.  
  69. if(($tipo_patente=="ALL")and ($valor_patente_desde<>NULL) and ($valor_patente_hasta<>NULL) and ($antiguedad_desde==NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  70.   {
  71.   //echo "siete";
  72.   $sql="SELECT * FROM patentes WHERE valor >= $valor_patente_desde AND valor <=$valor_patente_hasta ORDER BY valor ASC";
  73.   }
  74.  
  75. if(($tipo_patente<>"ALL")and ($valor_patente_desde<>NULL) and ($valor_patente_hasta<>NULL) and ($antiguedad_desde==NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  76.   {
  77.   //echo "ocho";
  78.   $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' AND valor >= $valor_patente_desde AND valor <=$valor_patente_hasta ORDER BY valor ASC";
  79.   }
  80.  
  81. if(($tipo_patente=="ALL")and ($valor_patente_desde==NULL) and ($valor_patente_hasta==NULL) and ($antiguedad_desde<>NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  82.   {
  83.   //echo "nueve";
  84. $sql="SELECT * FROM patentes WHERE fecha_otorg LIKE '%$antiguedad_desde%' ORDER BY n_patente ASC";
  85.   }
  86.  
  87. if(($tipo_patente<>"ALL")and ($valor_patente_desde==NULL) and ($valor_patente_hasta==NULL) and ($antiguedad_desde<>NULL) and ($antiguedad_hasta==NULL)  and ($capital_desde==NULL) and ($capital_hasta==NULL) and ($n_trabajadores==NULL) and ($sucursales=="ALL"))
  88.   {
  89.   //echo "diez";
  90. $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' AND fecha_otorg LIKE '%$antiguedad_desde%' ORDER BY n_patente ASC";
  91.   }
  92.  
  93.  
  94.  

si se dan cuenta aqui ya llevo 10 tipos de consulta y lo que quiero hacer es que se simplifique en una sola, espero que me puedan guiar o decir como lo puedo solucionar, muchas gracias desde ya por leer este post,
saludos,
Neo.
Un Tigre Nunka Kambia Sus Rayas

Mollense

  • Miembro de PLATA
  • *****
  • Mensajes: 1755
  • Nacionalidad: ar
    • Ver Perfil
    • http://solocodigo.com/
Re: Problema Con Consulta
« Respuesta #1 en: Martes 25 de Septiembre de 2007, 01:55 »
0
¿Que tal neorent?

Te alegrarás de saber que no es necesario realizar todas las combinaciones posibles para formar tu consulta.
Te aclaro antes de darte mi idea, que no se cuales sean los tipos de datos de los campos de tu DB, pero si entendés la idea no vamos a tener problemas :).

La idea es que solamente preguntes una vez el valor de cada campo y de acuerdo al resultado de esa comparación, concatenes o no la restricción a la consulta sql:

Código: Text
  1. $tipo_patente=$_GET['tipo_patente2'];
  2. $valor_patente_desde=$_GET['valor_patente_desde'];
  3. $valor_patente_hasta=$_GET['valor_patente_hasta'];
  4. $antiguedad_desde=$_GET['antiguedad_desde'];
  5. $antiguedad_hasta=$_GET['antiguedad_hasta'];
  6. $capital_desde=$_GET['capital_desde'];
  7. $capital_hasta=$_GET['capital_hasta'];
  8. $n_trabajadores=$_GET['n_trabajadores'];
  9. $sucursales=$_GET['sucursales'];
  10.  
  11. $sql="SELECT * FROM patentes";
  12. $where="WHERE ";
  13.              
  14. //Comprobamos los campos y vamos formando los criterios
  15. if($tipo_patente<>"ALL")$where.= "tipo_patente='$tipo_patente' AND ";
  16. if($valor_patente_desde<>NULL)$where.= "valor >='$valor_patente_desde' AND ";
  17. if($valor_patente_hasta<>NULL)$where.= "valor <='$valor_patente_hasta' AND ";
  18. if($antiguedad_desde<>NULL)$where.= "valor >='$antiguedad_desde' AND ";
  19. if($antiguedad_hasta<>NULL)$where.= "valor <='$antiguedad_hasta' AND ";
  20. if($capital_desde<>NULL)$where.= "valor >='$capital_desde' AND ";
  21. if($capital_hasta<>NULL)$where.= "valor <='$capital_hasta' AND ";
  22. if($n_trabajadores<>NULL)$where.= "n_trabajadores='$n_trabajadores' AND ";
  23. if($sucursales<>"ALL")$where.= "sucursales='$sucursales' AND ";
  24.  
  25. //Si existe por lo menos un criterio la variable $where será distinta a su valor inicial "WHERE "
  26. if($where<>"WHERE "){
  27.   //eliminamos el último " AND "
  28.   $where=substr($where,0,strlen($where)-5);
  29.   //concatenamos los criterios a la consulta
  30.   $sql.=" $where";
  31.   //agregamos el criterio de ordenación
  32.   $sql.=" ORDER BY n_patente ASC";
  33. }
  34.  
  35. echo "SQL: $sql";
  36.  

Bueno, eso es lo que se me ocurre ahora, tal vez (muy probable) se pueda mejorar...

Espero sea de utilidad.

Un saludo :beer:
"Los que renuncian son más numerosos que los que fracasan" H.F.
"No se cómo sería la III Guerra Mundial, pero la cuarta sería con piedras" A.E.
"Quién no fía no es de fiar..."


...no te quedes mirando.

neorent

  • Miembro MUY activo
  • ***
  • Mensajes: 249
    • Ver Perfil
    • http://www.laestokada.cl
Re: Problema Con Consulta
« Respuesta #2 en: Martes 25 de Septiembre de 2007, 18:14 »
0
muchas gracias me sirvio mucho, vere si puedo mejorarla y despues la subo para que los demas tambien la ocupen,
saludos y nuevamente gracias,
neo.
Un Tigre Nunka Kambia Sus Rayas

Mollense

  • Miembro de PLATA
  • *****
  • Mensajes: 1755
  • Nacionalidad: ar
    • Ver Perfil
    • http://solocodigo.com/
Re: Problema Con Consulta
« Respuesta #3 en: Miércoles 26 de Septiembre de 2007, 00:07 »
0
Cita de: "neorent"
muchas gracias me sirvio mucho, vere si puedo mejorarla y despues la subo para que los demas tambien la ocupen,
saludos y nuevamente gracias,
neo.
Un placer :beer:
"Los que renuncian son más numerosos que los que fracasan" H.F.
"No se cómo sería la III Guerra Mundial, pero la cuarta sería con piedras" A.E.
"Quién no fía no es de fiar..."


...no te quedes mirando.