To avoid mistakes like that, it is convenient to write the most organized code, in a way that allows you to check the uniformity in a single view, for example:
$strHTML="";
while ($registro = $resultado->fetch(PDO::FETCH_ASSOC)) {
$strHTML.="Nombre Artículo: " . $registro['NOMBREARTÍCULO'] .
"Sección: " . $registro['SECCIÓN'] .
"Precio: " . $registro['PRECIO'] .
"País de origen: " . $registro['PAÍSDEORIGEN'] . "<br>";
}
echo $strHTML;
So you can see if any% of concatenation% is missing, if in some of the values you are missing the .
, as was the case of :
, etc.
As a recommendation, avoid the use of accents or País de origen
in variable names or tables or columns of the database, it can be problematic in scenarios where you neglect to handle coding well.
EDITION WITH RESPECT TO THE NEW ERROR
The new error emerged:
Fatal error: Call to a member function prepare () on string
is because in this line:
$base=exec("SET CHARACTER SET utf8");
Instead of applying the ñ
command, what you do is equal the variable exec("SET CHARACTER SET utf8")
to the result of that command. That is, by doing that, $base
does not represent your connection object, but it is a simple string.
This can be resolved simply like this:
$base->exec("SET CHARACTER SET utf8");
But it is much better to permanently configure your PDO object once and for all, passing it an array of options with the necessary configurations and indicating the charset within the dsn. That way, you do not have to keep invoking methods to apply more configurations once the object is created.
What we will do is create an array that includes both this $base
and another very important configuration that is to set the emulated preparations to setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
. PDO brings FALSE
by default and with this option in TRUE
some skilled can colernos harmful SQL instructions emulating prepared queries.
The code would look like this:
<?php
try {
$dsn = "mysql:host=localhost;dbname=pruebas;charset=utf8";
$arrOptions = array(
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$base=new PDO($dsn, 'root', '',$arrOptions);
$sql = "SELECT NOMBREARTÍCULO, SECCIÓN, PRECIO, PAÍSDEORÍGEN
FROM PRODUCTOS WHERE NOMBREARTÍCULO = ?";
$resultado = $base->prepare($sql);
$resultado->execute(array("Destornillador"));
$strHTML="";
while ($registro = $resultado->fetch(PDO::FETCH_ASSOC)) {
$strHTML.="Nombre Artículo: " . $registro['NOMBREARTÍCULO'] .
"Sección: " . $registro['SECCIÓN'] .
"Precio: " . $registro['PRECIO'] .
"País de origen: " . $registro['PAÍSDEORIGEN'] . "<br>";
}
echo $strHTML;
$resultado->closeCursor();
} catch(Exception $e) {
die('Error: ' . $e->getMessage());
}
?>