php and query query

1

I have a form with which according to the data that you get, you get information from a database. My problem is that if I do not enter any data (I do not put min1) I get all the information, when I should leave a message with "the table is empty which is what I have put as a condition. Can you help me to know that I have done wrong please?

<html>

<head>
    <title>FormularioPDO4 para consultar en la Base de Datos eligiendo una tabla</title>
</head>

<body>
<p><h4>Los articulos con un precio mayor o igual a este son:</h4></p>

    <?php

include("datosconexion.php");


$gd= new PDO($dsn,$usuario,$contrasena);


$min1=$_POST['min1'];


$consulta= "SELECT * FROM articulo WHERE :min1<=pvp";

$resultadoConsulta = $gd->prepare($consulta);
$resultadoConsulta->bindParam(':min1', $min1);


$ok=$resultadoConsulta->execute();

if($ok) {
    if($resultadoConsulta->rowcount()!=0){

        $n=$resultadoConsulta->columnCount();

        foreach($resultadoConsulta as $fila){

            echo"<p>";

            for($i=0;$i<$n;$i++){
                echo $fila[$i],"&nbsp","&nbsp","\t";
            }
            echo "</p>";
        }

    }else{
         echo "La tabla esta vacia";
    }
}
else echo "Error en la consulta";

$gd=null;
?>


    </body>
</html>
    
asked by Maria 23.12.2018 в 12:24
source

2 answers

1

I have put a comment on it, but I extend it a bit:

/* Usamos un operador ternario para determinar si existe la variable que,
en principio, debería llegar por $_POST desde el formulario que mencionas.
Como no citas el tipo de campo, si es un checkbox o radio button podría no 
llegar, si el usuario no marca una casilla o botón). 
Por lo tanto, lo primero, es estar seguros de que tenemos esa variable en 
$_POST.
Si no la tenemos, le damos, por defecto, un valor como cadena vacía. */    
$min1 = (isset($_POST["min1"])?$_POST["min1"]:"";

if ($min1 > "") // Si el valor de $min1 tiene algo que sea más que una cadena vacía
{
    // Hacemos la consulta
} else { / Si era un cadena vacía
    // No hacemos la consulta y mostramos un mensaje de notificación
}

If I have correctly understood your question, we will resolve it with this.

    
answered by 23.12.2018 в 16:16
1

I see a few problems with your code, some are logic, some are syntax, some are optimization.

I list them briefly in order of appearance:

  • If the query depends on whether there is POST or not, you must subordinate the include and the creation of the connection instance to that validation, otherwise you will be using resources without even knowing if you are going to need them. It is an error of optimization and good practices.
  • To evaluate the POST it is preferable to use empty . It will not fill you with the message log if you try to find a key that does not exist. Here a ternary with empty is used to evaluate the data and save it in a variable.
  • The query as it was is not correct. The :nombre markers do not apply on column names, but on values. What replaces the marker is the value, not the column.
  • In SELECT it is appropriate to name the columns explicitly. You will avoid selecting columns that you do not need and then resorting to obscure procedures to display the data. For any future programmer that is not you and needs to review your code, the procedure you use to show each column will be obscure, incomprehensible ... because things are not called by their name. Even yourself, when you review that code, after a while, you will know exactly what is being printed. NOTE: I have used two columns (imaginary) that are nombre and tipo to give clarity to the code. You must change them for the actual columns you need. I have also used PDO::FETCH_ASSOC to retrieve the values of each column by name.
  • Throughout the code I used a variable $html that will be responsible for saving the results obtained. In the end that variable is printed.
  • I have moved the title Los artículos con un precio mayor... to the corresponding place in the logic of the program. That title should not be displayed if there are no rows in the query.

The proposed code is this, I hope it is useful and serves to clarify concepts and implement good programming practices:

    <html>
    <head>
        <title>FormularioPDO4 para consultar en la Base de Datos eligiendo una tabla</title>
    </head>

    <body>

    <?php
    $min1=( empty($_POST['min1']) ) ? NULL : $_POST['min1'];

    if ( $min1 ) {
        /*
            Gestionamos la conexión aquí
            porque estamos seguros de que se necesitará
        */
        include("datosconexion.php");
        $gd= new PDO($dsn,$usuario,$contrasena);
        /*
            1. Aquí había un error, el marcador de :nombre es para el valor, 
               no para el nombre de la columna
               Si la columna se llama pvp cámbialo a la izquierda
            2. Conviene poner en el SELECT las columnas específicas que necesita
               así evitas procedimientos complicados como contar luego el total de columnas
               y además no seleccionas columnas que no necesites
               Aquí pongo como ejemplo dos columnas: nombre, tipo... 
               debes poner en el SELECT los nombres reales de tus columnas
        */
        $consulta= "SELECT nombre,tipo FROM articulo WHERE min1<=:min1";
        if ( $resultadoConsulta = $gd->prepare($consulta) ) {
            $resultadoConsulta->bindParam(':min1', $min1);
            if ($ok=$resultadoConsulta->execute() ){
                if($resultadoConsulta->rowcount()!=0){
                    $html="<h4>Los artículos con un precio mayor o igual a este son:</h4>";
                    while ($fila = $resultadoConsulta->fetch(PDO::FETCH_ASSOC)) {
                        /*
                            Aquí asignamos las columnas ESPECÍFICAS del SELECT
                            por favor actualiza con los nombres reales de tus columnas
                        */
                        $nombre=$fila["nombre"];
                        $tipo=$fila["tipo"];
                        $html.="<p>$nombre&nbsp&nbsp\t$tipo</p>";
                    }
                } else {
                    $html.="La tabla esta vacía";
                }
            } else {
                $html.="Error ejecutando la consulta";
            }
        } else { 
            $html.="Error preparando"; 
        }
        $gd=null;       
    } else {
        $html.="No se posteó min1";
    }
    echo $html;
?>
    </body>
</html>
    
answered by 05.01.2019 в 14:04