Requête préparé PHP/MYSQL

Par Martin40, il y a 5 ans


Bonjour,

J'ai un petit soucis avec ma requête préparée.

function product_price_get($table, $column, $product_id){ global $bdd; $req = $bdd->prepare("SELECT * FROM :table WHERE :column = :product_id"); $req->BindParam(':table',$table); $req->BindParam(':column',$column); $req->BindParam(':product_id',$product_id); $req->execute(); $product_price = $req->fetch(PDO::FETCH_ASSOC); return $product_price; }

J'obtiens l'erreur suivante :

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 MySQL server version for the right syntax to use near ''app_gc_produits' WHERE 'prix_boite_ht' = '10'' at line 1 in /var/www/model/product_price_get.php:9 Stack trace: #0 /var/www/model/product_price_get.php(9): PDOStatement->execute() #1 /var/www/html/controller/testfonction.php(10): product_price_get('app_gc_produits', 'prix_boite_ht', '10') #2 /var/www/html/view/structure.php(19): require('/var/www/html/c...') #3 /var/www/html/index.php(21): require('/var/www/html/v...') #4 {main} thrown in /var/www/model/product_price_get.php on line 9 $table = 'app_gc_produits' $column = 'prix_boite_ht' $product_id = '10'

Je ne trouve pas d'où vient mon erreur, le sauriez vous ?

Merci d'avance,

4 réponses

Carouge10, il y a 5 ans

Bonsoir,
Tu ne peux pas binder des noms de champs/table

Martin40, il y a 5 ans

Voilà qui répond à ma question merci !

Du coup je suis parti la dessus :

<?php function product_price_get($table, $column, $product_id){ global $bdd; $req = $bdd->prepare("SELECT * FROM $table WHERE $column = :product_id"); $req->BindParam(':product_id',$product_id); $req->execute(); $product_price = $req->fetch(PDO::FETCH_ASSOC); return $product_price; }
Carouge10, il y a 5 ans

attention quand même aux injections sql suivant d'où proviennent tes données

Martin40, il y a 5 ans

Effectivement,

J'ai donc scindé en deux mes fonctions et mis en dure le nom de la table et de la colonne ;)