Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''inventory' WHERE 'Inv_User' = 'gmarsi'' at line 1 in C:\xampp\htdocs\qbc_web\funciones\funciones_contador.php:14 Stack trace: #0 C:\xampp\htdocs\qbc_web\funciones\funciones_contador.php(14): PDOStatement->execute() #1 C:\xampp\htdocs\qbc_web\login\profile.php(75): contarElementos('Inv_User', 'inventory', 'Inv_User', 'gmarsi') #2 {main} thrown in C:\xampp\htdocs\qbc_web\funciones\funciones_contador.php on line 14
Me da este error al generar la consulta, el código es este:
function contarElementos($element, $table, $condition, $purchased){
require(realpath($_SERVER["DOCUMENT_ROOT"]) .'/qbc_web/datos_conexion.php');
$consulta = "SELECT COUNT(:element) AS Contador FROM :table WHERE :condition = :purchased";
$result = $base -> prepare($consulta);
$result -> bindValue(':element', $element);
$result -> bindValue(':table', $table);
$result -> bindValue(':condition', $condition);
$result -> bindValue(':purchased', $purchased);
$result -> execute();
$sql_contador = $result->rowCount();
if($sql_contador < 1){
return 0;
}else{
while($fila = $result -> fetch(PDO::FETCH_ASSOC)){
return $fila['Contador'];
}
}
// echo $consulta;
}
La función básicamente lo que hace es contar los elementos de X tabla teniendo en cuenta los parámetros que se le introducen. Como se puede ver en el error aparece contarElementos('Inv_User', 'inventory', 'Inv_User', 'gmarsi')
que son los parámetros que quiero que use la función para hacer la consulta a la base de datos. A qué se debe esto?
SELECT COUNT(:element) AS Contador FROM :table WHERE :condition
a lo sumo debería ser algo como:SELECT COUNT($element) AS Contador FROM $table WHERE $condition ...
guardado de pasar los valores en parámetros, eso es lo más importante de cara a la Inyeccion SQL.