I have a piece of code that should display results of a query sql
to a table, but when doing the query I get the error
Uncaught Error: Call to a member function fetchAll() on boolean in /home/public_html/app/php/con-top-header.php:32 Stack trace: #0 /home/public_html/app/index.php(1) : include() #1 {main} thrown in /home/public_html/app/php/con-top-header.php on line 32
I have to say that I have several queries created in the same way and I have no problem, neither with the variable $conn
nor with$u_e_id_show
<?php foreach ($assign_rows as $row) { ?>
<option value="1"><?php echo $row['u_nombre']; ?></option>
<?php } ?>
`
// Extraer datos de usuarios si el ID de empresa coincide con el usuario
$assign_sql = "SELECT * FROM usuarios WHERE u_empresaID='$u_e_id_show' ORDER BY id DESC";
$assign_result = $conn->query($assign_sql);
$assign_rows = $assign_result->fetchAll();
And here the fileconexion
<?php
function dbConnect (){
$conn = null;
$host = '*******';
$db = '*******';
$user = '*******';
$pwd = '*******';
try {
$conn = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);
}
catch (PDOException $e) {
echo 'Excepción capturada: ', $e->getMessage(), "\n";
exit;
}
return $conn;
}
?>
query()
it returns a PDOStatement object (the data obtained in the query we could say) orFALSE
if an error occurs. Therefore, that possibility should be controlled in the code.For example, here we evaluate the state, assigning the data to the variable or an error message (which could be an array with an error key in case you are working with an API or an asynchronous call from the client).
Shield the code against malicious attacks
I must say that your code is vulnerable to SQL Injection attacks . You should never pass variables in queries directly. For these cases it is recommended to use prepared queries.
Here basically the query is prepared by replacing the data itself with a marker
?
and the data is passed in the form of an array in theexecute
. All of this is explained in detail in the PHP Manual and in various questions on this very site.