Programación Web y Scripting > PHP
Problema Con Consulta
(1/1)
neorent:
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 --- <?<form name="b_avanzada" action="b_patentes1.php" method="get" > <table width="100%"><tr><td colspan="2" ><div align="center">BÚSQUEDA PATENTES </div></td></tr> <tr> <td width="252">TIPO PATENTE </td> <td width="372" > <label> <select name="tipo_patente2" id="tipo_patente2"> <option value="ALL">SELECCIONE TIPO PATENTE...</option> <option value="ALCOH">PATENTES ALCOHOL</option> <option value="COMER">PATENTES COMERCIALES</option> <option value="ESTAC">PATENTES DE ESTACIONAMIENTO</option> <option value="FERIA">PATENTES DE FERIAS LIBRES</option> <option value="INDUS">PATENTES INDUSTRIALES</option> <option value="PROFE">PATENTES DE PROFESIONALES</option> <option value="PROPA">PATENTES DE PROPAGANDA</option> </select> </label> <label></label></td> </tr> <tr> <td >VALOR PATENTE </td> <td><label>DESDE <input name="valor_patente_desde" type="text" id="valor_patente_desde" size="12"> </label> HASTA <label> <input name="valor_patente_hasta" type="text" id="valor_patente_hasta" size="12"> </label></td> </tr> <tr> <td>CAPITAL</td> <td><span class="Estilo6">DESDE</span> <input name="capital_desde" type="text" id="capital_desde" size="12" /> <span class="Estilo6">HASTA</span> <input name="capital_hasta" type="text" id="capital_hasta" size="12" /> <label></label></td> </tr> <tr> <td class="Estilo6">Nº TRABAJADORES </td> <td><input name="n_trabajadores" type="text" id="n_trabajadores" size="12" /> <label></label></td> </tr> <tr> <td class="Estilo6">SUCURSALES FUERA DE SANTIAGO </td> <td><? sucursales()?></td> </tr> <tr> <td colspan="2" class="Estilo6" align="center"> <label> <input name="Submit" type="submit" class="Estilo6" value="Buscar" /> <input name="Limpiar" type="reset" class="Estilo6" id="Limpiar" value="Limpiar" /> <input name="Volver" type="button" class="Estilo6" id="Volver" value="Volver" onclick="volver()" /> <input name="antiguedad_desde" type="hidden" id="antiguedad_desde" value="" /> <input name="antiguedad_hasta" type="hidden" id="antiguedad_hasta" value="" /> </label></td> </tr></table></form><?function sucursales(){ $link = mysql_connect("localhost", "intranet", "intranet"); mysql_select_db("db_clt_municipales", $link); $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"); // Voy imprimiendo el primer select compuesto por los paises echo "<select name='sucursales' id='sucursales'>"; echo "<option value='ALL'>Sucursales...</option>"; while($registro=mysql_fetch_row($sql)) { if ($registro[1]==NULL) { echo; } else { echo "<option value='".$registro[1]."'>".$registro[1]."</option>"; } } echo "</select>";}?><script>function volver(){setTimeout("<?php echo "location.href='menu.php'";?>", 1);}</script>
y este es donde hago la busqueda
b_patentes1.php
--- Código: Text --- //////////////////////////////////////////////////////Convierte fecha de mysql a normal////////////////////////////////////////////////////function cambiaf_a_normal($fecha){ ereg( "([0-9]{2,4})-([0-9]{1,2})-([0-9]{1,2})", $fecha, $mifecha); $lafecha=$mifecha[3]."/".$mifecha[2]."/".$mifecha[1]; return $lafecha;} //////////////////////////////////////////////////////Convierte fecha de normal a mysql//////////////////////////////////////////////////// function cambiaf_a_mysql($fecha){ ereg( "([0-9]{1,2})/([0-9]{1,2})/([0-9]{2,4})", $fecha, $mifecha); $lafecha=$mifecha[3]."-".$mifecha[2]."-".$mifecha[1]; return $lafecha;}$a="01"."/"."01"."/";$tipo_patente=$_GET['tipo_patente2'];$valor_patente_desde=$_GET['valor_patente_desde'];$valor_patente_hasta=$_GET['valor_patente_hasta'];$antiguedad_desde=$_GET['antiguedad_desde'];$antiguedad_hasta=$_GET['antiguedad_hasta'];$capital_desde=$_GET['capital_desde'];$capital_hasta=$_GET['capital_hasta'];$n_trabajadores=$_GET['n_trabajadores'];$sucursales=$_GET['sucursales'];$link = mysql_connect("localhost","intranet","intranet");mysql_select_db("db_clt_municipales",$link); 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")) { //echo "uno"; $sql="SELECT * FROM patentes ORDER BY n_patente ASC"; } 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")) { //echo "dos"; $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' ORDER BY n_patente ASC"; } 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")) { //echo "tres"; $sql="SELECT * FROM patentes WHERE (valor >='$valor_patente_desde') ORDER BY valor ASC"; } 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")) { //echo "cuatro"; $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' AND (valor >='$valor_patente_desde') ORDER BY valor ASC"; } 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")) { //echo "cinco"; $sql="SELECT * FROM patentes WHERE (valor <= '$valor_patente_hasta') ORDER BY valor ASC"; } 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")) { //echo "seis"; $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' AND (valor <= '$valor_patente_hasta') ORDER BY valor ASC"; } 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")) { //echo "siete"; $sql="SELECT * FROM patentes WHERE valor >= $valor_patente_desde AND valor <=$valor_patente_hasta ORDER BY valor ASC"; } 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")) { //echo "ocho"; $sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' AND valor >= $valor_patente_desde AND valor <=$valor_patente_hasta ORDER BY valor ASC"; } 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")) { //echo "nueve";$sql="SELECT * FROM patentes WHERE fecha_otorg LIKE '%$antiguedad_desde%' ORDER BY n_patente ASC"; } 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")) { //echo "diez";$sql="SELECT * FROM patentes WHERE tipo_patente='$tipo_patente' AND fecha_otorg LIKE '%$antiguedad_desde%' ORDER BY n_patente ASC"; }
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.
Mollense:
¿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 ---$tipo_patente=$_GET['tipo_patente2'];$valor_patente_desde=$_GET['valor_patente_desde'];$valor_patente_hasta=$_GET['valor_patente_hasta'];$antiguedad_desde=$_GET['antiguedad_desde'];$antiguedad_hasta=$_GET['antiguedad_hasta'];$capital_desde=$_GET['capital_desde'];$capital_hasta=$_GET['capital_hasta'];$n_trabajadores=$_GET['n_trabajadores'];$sucursales=$_GET['sucursales']; $sql="SELECT * FROM patentes";$where="WHERE "; //Comprobamos los campos y vamos formando los criteriosif($tipo_patente<>"ALL")$where.= "tipo_patente='$tipo_patente' AND ";if($valor_patente_desde<>NULL)$where.= "valor >='$valor_patente_desde' AND ";if($valor_patente_hasta<>NULL)$where.= "valor <='$valor_patente_hasta' AND ";if($antiguedad_desde<>NULL)$where.= "valor >='$antiguedad_desde' AND ";if($antiguedad_hasta<>NULL)$where.= "valor <='$antiguedad_hasta' AND ";if($capital_desde<>NULL)$where.= "valor >='$capital_desde' AND ";if($capital_hasta<>NULL)$where.= "valor <='$capital_hasta' AND ";if($n_trabajadores<>NULL)$where.= "n_trabajadores='$n_trabajadores' AND ";if($sucursales<>"ALL")$where.= "sucursales='$sucursales' AND "; //Si existe por lo menos un criterio la variable $where será distinta a su valor inicial "WHERE "if($where<>"WHERE "){ //eliminamos el último " AND " $where=substr($where,0,strlen($where)-5); //concatenamos los criterios a la consulta $sql.=" $where"; //agregamos el criterio de ordenación $sql.=" ORDER BY n_patente ASC";} echo "SQL: $sql";
Bueno, eso es lo que se me ocurre ahora, tal vez (muy probable) se pueda mejorar...
Espero sea de utilidad.
Un saludo :beer:
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.
Mollense:
--- 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.
--- Fin de la cita ---
Un placer :beer:
Navegación
Ir a la versión completa