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  \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>