Duda Seeker ID client php mysqli

0

I edit the post with the solution: SUMMARY: What we want is that when searching for the client id, show me the complete record of the client.

(Vary the table to taste or need) Code resolution to the problem:

      <form method="POST" action="" onSubmit="return validarForm(this)"> 
        <input type="text" placeholder="Ingresar código de cliente" name="palabra">     
        <input type="submit" value="Buscar" name="buscar">     
      </form>
      </center>
        <?php

        require('conexion.php');

        /* Variable para el control de errores*/
        $arrMensaje=array();
        /*
                *1ª evaluación: ¿la conexión está activa?
                *Este sería el primer paso antes de lanzar cualquier código
                *relativo a la base de datos
        */
        if ($mysqli){
            /*
                    *CONSULTA PARA PREPARAR
                    *En estas consultas en vez de los valores pone el signo ?
                    *Habrá tantos signos ?  como valores externos se requieran
                    *Aquí sólo se usa uno, pero pueden ser más
            */
            $buscar = $_POST["palabra"];
            $sql = "SELECT * FROM usuarios WHERE id like '%$buscar%'";
            /*
                    *VALORES
                    *Generalmente los valores son recuperados por $_POST o $_GET
                    *Aquí lo ponemos directamente por motivos de simplicidad
                    *Un valor recuperado por POST sería algo así más o menos: $id=$_POST["id"];
                    *La consulta buscará los actores cuyo id sea mayor que 0 y menor que 8
            */


            /*
                    *PREPARAR LA CONSULTA
            */

            $stmt=$mysqli->prepare($sql);

            /*
                    *2ª evaluación: ¿La consulta se preparó bien?
                    *Dado que el método prepare invocado antes devuelve FALSE
                    *si hay algún error, podemos preguntar si $stmt es TRUE
                    *Si no lo es, significa que hubo un error en la consulta
            */

            if ($stmt) {

                /*
                      * Si la consulta se preparó bien, ahora le pasamos aparte los valores
                      * Este es el núcleo de las consultas preparadas
                      * Se usa aquí bind_param para pasar los valores
                      * IMPORTANTE: Aquí se pasan tantos valores como signos de ? haya en la instrucción $sql
                      * como la instrucción tenía un sólo ?, pasamos un solo valor
                      * cuando hay más valores, estos deben pasarse en el orden en que aparecen en $sql
                      * Las "ii"  indican el tipo de dato de esa columna en la base de datos
                      * en este caso son numéricos, si fuesen cadenas, en vez de "i" habría "s"
                      * si fuese uno numérico y otro cadena entonces tendríamos "is", y así por el estilo...
                */

                $stmt->bind_param("i", $buscar); //Si idusuario es VARCHAR cambia la "i" por una "s"
                $stmt->execute();

                /*
                        * ALMACENAR LOS RESULTADOS
                        * mysqli tiene un problema cuando se trata de almacenar los resultados
                        * en arrays asociativos usando consultas preparadas
                        * por eso es invocado aquí el método get_result hecho a mano
                        * ya que éste sólo funciona en servidores con mysqlnd instalado
                        * el método get_result puede ser guardado en una clase utilitaria
                        * y llamarlo mediante una nueva instancia de esa clase cuando lo necesitemos
                        * o, si hacemos muchas operaciones de este tipo, recomiendo pasar de mysqli a PDO
                */

                $arrResultado=get_result($stmt);

                /*
                        * CONSTRUIR LA TABLA
                        * En vez de mezlcar constantemente código HTML/PHP
                        * Lo cual hace el código más difícil de leer y analizar
                        * Podemos crear toda nuestra tabla en una variable PHP que iremos concatenando
                        * Y la imprimimos al final
                */


                /* Primera parte de nuestra tabla */
                $strHTML='<table>
                                <thead>
                                    <th >Codigo</th>
                                    <th >Optica</th>
                                    <th >Nombre</th>
                                    <th >Apellidos</th>
                                    <th >Provincia</th>
                                    <th >Agente</th>
                                    <th >Telefono</th>                            
                                 </thead>
                                 <tbody>';

                /* Leemos el array obtenido antes y seguimos concatenando cada fila/columnas */


                foreach ($arrResultado as $row)
                {
                    $strHTML.='<tr>';
                    $strHTML.='<td>'.$row["id"]."</td>";
                    $strHTML.='<td>'.$row["ncomercial"]."</td>";
                    $strHTML.='<td>'.$row["nombre"]."</td>";
                    $strHTML.='<td>'.$row["apellidos"]."</td>";
                    $strHTML.='<td>'.$row["provincia"]."</td>";
                    $strHTML.='<td>'.$row["asignaragente"]."</td>";
                    $strHTML.='<td>'.$row["telefono"]."</td>";
                    $strHTML.='</tr>';

                }

                /* Una vez fuera del bucle, completamos la tabla */

                $strHTML.='</tbody>';
                $strHTML.='</table>';

                /*Completada la tabla, la imprimimos*/

                echo $strHTML;

                /* Cerramos el $stmt */

                $stmt->close();

            }else{

                /*
                    * Llenamos el array de control de errores con un mensaje
                    * Podemos usar el método error de $mysqli para saber qué error es
                */

                $arrMensaje=array("error"=>"Hubo un fallo en la consulta: ".$mysqli->error);

            }


            /* Cerramos la conexión */

            $mysqli->close();


        }else{

                /*
                    * Llenamos el array de control de errores con un mensaje
                    * Podemos usar el método error de $mysqli para saber qué error es
                */

            $arrMensaje=array("error"=>"La conexión es nula: ".$mysqli->error);
        }


        /* 
            * VERIFICAR SI HUBO ERROR
            * Aquí leemos $arrMensaje para ver si contiene algo
            * Si hay algo significa que algún error fue capturado en la ejecución del código
            * entonces podremos imprimirlo
            * Esta forma de proceder la he copiado de los servicos REST, que siempre devuelven algo
            * es una buena práctica hacer decir siempre algo al código
            * o sea, no escribir código mudo cuando falle algo
        */
        if ($arrMensaje){
            echo $arrMensaje["error"];
        }


        /*
            * FUNCION QUE EMULA EL FETCH_ASSOC DE PDO
            * Esta función nos permite crear un array asociativo con los resultados
            * Así accedemos fácimente a su valor por el nombre de columna en la base de datos
        */

        function get_result( $Statement ) {
            $RESULT = array();
            $Statement->store_result();
            for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
                $Metadata = $Statement->result_metadata();
                $PARAMS = array();
                while ( $Field = $Metadata->fetch_field() ) {
                    $PARAMS[] = &$RESULT[ $i ][ $Field->name ];
                }
                call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
                $Statement->fetch();
            }
            return $RESULT;
        }
        ?>
    
asked by Javier Avila Fernandez 06.11.2017 в 12:33
source

1 answer

0

The problem would be solved with three simple steps:

  • Write your $sql as a prepared query. For so many times said about SQL Injection:

    $sql = "SELECT * FROM usuarios WHERE id LIKE ?";
    
  • Prepare well the variable that you will spend to use with LIKE . Note that in prepared queries the % that surround the value that LIKE will evaluate are placed in the variable, not in the query itself:

    $buscar='%'.$_POST["palabra"].'%'; 
    
  • It is necessary to change the type of data that is passed in bind_param . Since we will be passing a string, we change the i to the s :

    $stmt->bind_param("s", $buscar);
    
  • With this the code will not only work, but it will be a secure code.

  • Finally, the code lacks supplementary control. What happens if the search criteria are not met? Currently the code will present you with a table only with headers in that case. That part can be controlled in the following way:

    After obtaining the results:

    $arrResultado=get_result($stmt);
    
  • We check if $arrResultado is not blank before constructing the table:

        if ($arrResultado){
                $strHTML='<table>
                                <thead>
                                    <th >Codigo</th>
                                    <th >Optica</th>
                                    <th >Nombre</th>
                                    <th >Apellidos</th>
                                    <th >Provincia</th>
                                    <th >Agente</th>
                                    <th >Telefono</th>                            
                                 </thead>
                                 <tbody>';
    
                /* Leemos el array obtenido antes y seguimos concatenando cada fila/columnas */
    
    
                foreach ($arrResultado as $row)
                {
                    $strHTML.='<tr>';
                    $strHTML.='<td>'.$row["id"]."</td>";
                    $strHTML.='<td>'.$row["ncomercial"]."</td>";
                    $strHTML.='<td>'.$row["nombre"]."</td>";
                    $strHTML.='<td>'.$row["apellidos"]."</td>";
                    $strHTML.='<td>'.$row["provincia"]."</td>";
                    $strHTML.='<td>'.$row["asignaragente"]."</td>";
                    $strHTML.='<td>'.$row["telefono"]."</td>";
                    $strHTML.='</tr>';
    
                }
    
                /* Una vez fuera del bucle, completamos la tabla */
    
                $strHTML.='</tbody>';
                $strHTML.='</table>';
    
                /*Completada la tabla, la imprimimos*/
    
                echo $strHTML;
        }else{
            $arrMensaje=array("error"=>"No se cumplieron los criterios de búsqueda");
        }
    
        
    answered by 06.11.2017 / 13:48
    source