Filter a query using the option selected in INPUT SELECT

0

I am wanting to filter queries through what I select in a SELECT input, because I need to make queries through different options (CEDULA, NAME, LAST NAME, AGE, ETC ...) They recommended me to use OR for that, but it is not just what I need.

It occurred to me (I do not know if it is possible and that is why I write this) that when selecting the option, and executing the search through an IF, I took what I selected and executed the search under that parameter, I do not know if it is possible ( And if it is not done, I would appreciate it if you help me.

I leave the code that I currently have.

<?php
    $TIPO_BUSQUEDA = $_POST["TIPO_BUSQUEDA"];
    function ejecuta_consulta($labusqueda)
    {
        include("conexiond.php");

        $conexion= mysqli_connect($db_host, $db_usuario, $db_contra);

        if (mysqli_connect_errno()) {
            echo "Fallo al conectar con la base de datos";
            exit();
        }

        mysqli_select_db($conexion, $db_nombre) or die("No se encuentra la base de datos.");


        $consulta = "SELECT datosbasicos.CED_PAC,datosbasicos.NOM_PAC,datosbasicos.APE_PAC,datosbasicos.SEX_PAC,datosmedicos.COD_CONSULTA,datosmedicos.ALT_PAC,datosmedicos.PESO_PAC,datosmedicos.FECHA,datosmedicos.TIPO_CONSULTA,datosmedicos.SINTOMAS,datosmedicos.OBSERV,datosmedicos.HIS_PAC,datosmedicos.MEDI_PAC,datosmedicos.OPERADO,datosmedicos.ALERGIAS FROM datosbasicos INNER JOIN datosmedicos ON datosbasicos.CED_PAC=datosmedicos.CED_PAC WHERE datosbasicos.NOM_PAC LIKE '%$labusqueda%' OR datosbasicos.CED_PAC LIKE '%$labusqueda%' OR datosmedicos.COD_CONSULTA LIKE '%$labusqueda%' OR datosbasicos.CED_PAC LIKE '%$labusqueda%' OR datosmedicos.FECHA LIKE '%$labusqueda%'  ";

        $resultados = mysqli_query($conexion, $consulta);

        $filas = array(); // Crea la variable $filas y se le asigna un array vacío
        // (Si la consulta no devuelve ningún resultado, la función por lo menos va a retornar un array vacío)

        while ($fila=mysqli_fetch_array($resultados, MYSQLI_ASSOC)) {
            $filas[] = $fila; // Añade el array $fila al final de $filas
        }

        mysqli_close($conexion);

        return $filas; // Devuelve el array $filas
    }
?>

<!DOCTYPE html>
<html>

<head>
    <title>Sistema de historias médicas - Dr. Darling Davila</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/estilo.css">
    <link href="https://fonts.googleapis.com/css?family=Lato|Roboto" rel="stylesheet">
</head>

<body>
    <?php
        $mibusqueda=$_GET["buscar"];

        $mipag=$_SERVER["PHP_SELF"];

        if ($mibusqueda!=null) {
            $pacientes = ejecuta_consulta($mibusqueda);
    ?>

        <div id="main-container">
        <img src='imagenes/header.png' class='img'>
            <table>
                <thead>
                    <tr>
                        <th>Codigo Consulta</th>
                        <th>Fecha</th>
                        <th>Cedula</th>
                        <th>Nombres</th>
                        <th>Apellidos</th>
                        <th>Sexo</th>
                        <th>Altura</th>
                        <th>Peso</th>
                        <th>Sintomas</th>
                        <th>Observaciones</th>
                        <th>Tipo de consulta</th>
                        <th>Medicamentos actuales</th>
                        <th>Alergias</th>
                        <th>Operado</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Si la variable $pacientes esta definida y no está vacía
                    if (isset($pacientes) && !empty($pacientes)) {
                        // Recorre cada $paciente dentro del array $pacientes
                        foreach ($pacientes as $paciente) {
                            ?>
                        <tr>
                            <td><?php echo $paciente['COD_CONSULTA'] ?></td>
                            <td><?php echo $paciente['FECHA'] ?></td>
                            <td><?php echo $paciente['CED_PAC'] ?></td>
                            <td><?php echo $paciente['NOM_PAC'] ?></td>
                            <td><?php echo $paciente['APE_PAC'] ?></td>
                            <td><?php echo $paciente['SEX_PAC'] ?></td>
                            <td><?php echo $paciente['ALT_PAC'] ?></td>
                            <td><?php echo $paciente['PESO_PAC'] ?></td>
                            <td><?php echo $paciente['SINTOMAS'] ?></td>
                            <td><?php echo $paciente['OBSERV'] ?></td>
                            <td><?php echo $paciente['TIPO_CONSULTA'] ?></td>
                            <td><?php echo $paciente['MEDI_PAC'] ?></td>
                            <td><?php echo $paciente['ALERGIAS'] ?></td>
                            <td><?php echo $paciente['OPERADO'] ?></td>
                        </tr>
                    <?php
                        }
                    } ?>
                </tbody>
        </div>
    <?php
        } else {
            echo("<form action='". $mipag . "' method='GET'>
                <img src='imagenes/header.png'>
                    <h2>Busqueda de paciente</h2>
                    <div class='contenedor'>
                    <select name='TIPO_BUSQUEDA' class='input-100 text-center col-md-12'>
                        <option value='Cedula' selected='selected' <?PHP if($TIPO_BUSQUEDA=='Cedula'){ echo 'selected='selected'; } ?> Cedula</option>
                        <option value='Edad' <?PHP if($TIPO_BUSQUEDA=='Edad'){ echo 'selected='selected'; } ?> Edad</option>
                        <option value='Nombre' <?PHP if($TIPO_BUSQUEDA=='Nombre'){ echo 'selected='selected'; } ? >Nombre</option>
                        <option value='Fecha' <?PHP if($TIPO_BUSQUEDA=='Fecha'){ echo 'selected='selected'; } ?> Fecha</option>
                    </select>
                    <input type='text' name='buscar' class='input-100 text-center inline-block col-md-6 btn-enviar espacio-arriba'></label>

                    <input type='submit' name='enviando' value='Consulta' class='text-center inline-block col-md-12 espacio-arriba btn-enviar'>
                </div>
                </form>");
        }
     ?>

</body>

</html>
    
asked by Pablo Pernia 21.08.2017 в 05:11
source

1 answer

1

It would be a matter of building the SQL statement in two parts:

1st part:

You build the instruction up to WHERE :

$consulta = "SELECT datosbasicos.CED_PAC, datosbasicos.NOM_PAC, datosbasicos.APE_PAC, datosbasicos.SEX_PAC, 
datosmedicos.COD_CONSULTA, datosmedicos.ALT_PAC, datosmedicos.PESO_PAC, datosmedicos.FECHA, 
datosmedicos.TIPO_CONSULTA, datosmedicos.SINTOMAS, datosmedicos.OBSERV, datosmedicos.HIS_PAC, 
datosmedicos.MEDI_PAC, datosmedicos.OPERADO, datosmedicos.ALERGIAS 
FROM datosbasicos 
INNER JOIN datosmedicos ON datosbasicos.CED_PAC=datosmedicos.CED_PAC WHERE "; 

2nd part:

The 2nd part would be dynamic, it would depend on the element that has been selected, based on that you complete the query.

If your select has the following name tags: nom_pac, ced_pac, cod_consulta, fecha you would have to evaluate which of those elements has been passed in the _POST.

On the other hand, if you only want it to filter by an element, in the code where the select are you should create a code that deactivates the other select when choosing any other. Otherwise the code will work, but you will not have it under strict control.

Example:

//Variable booleana para saber si debe ejecutarse la consulta.
$bolEjecutar=true;

if ($_POST["nom_pac"])
{
    $consulta .="datosbasicos.NOM_PAC LIKE '%$labusqueda%'";

} elseif ($_POST["ced_pac"]) {

    $consulta .="datosbasicos.CED_PAC LIKE '%$labusqueda%'";

} elseif ($_POST["cod_consulta"]){

    $consulta .="datosmedicos.COD_CONSULTA LIKE '%$labusqueda%'";

}elseif ($_POST["fecha"]){

    $consulta .="datosmedicos.FECHA LIKE '%$labusqueda%'";

}else{

    //Esta condición se cumplirá cuando ningún select haya sido elegido
    //Establecemos la variable a false para que no se ejecute la consulta en ese caso
    $bolEjecutar=false;

}


if ($bolEjecutar)
{
     //Se ejecuta la consulta y se leen los datos
}else{
     //No se ejecuta la consulta porque ningún select fue escogido
}

In this way the query would remain with the criterion that exists in the select only.

Then you execute it.

  

Note: The query created in this way is vulnerable to Injection   SQL It is recommended to use prepared queries.

    
answered by 21.08.2017 в 18:01