Aide avec une classe

Eléphanteau du PHP | 16 Messages

23 déc. 2015, 13:31

Bonjour! Première question : est ce que ce code est correct car j'ai une erreur que Fatal error: Uncaught exception 'PDOException' with message '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 '' at line 1'?

Code : Tout sélectionner

class inserer { protected $DbHost; protected $DbName; protected $DbUser = 'root'; protected $DbPass = ''; protected $Table; public function __construct($Host, $Db, $tab) { $this->setDbHost($Host); $this->setDbName($Db); $this->setTable($tab); } public function setDbHost($host){ $this->DbHost = $host ; } public function setDbName($name){ $this->DbName = $name ; } public function setTable($tab){ $this->table = $tab ; } public function Connexion(){ try{ $dbh = new PDO("mysql:host=$this->DbHost;dbname=$this->DbName", $this->DbUser, $this->DbPass, array(PDO::ATTR_PERSISTENT => true)); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->exec("SET CHARACTER SET utf8"); } catch(Exception $e){ die('Erreur de connexion : '.$e->getMessage()); } } public function ShowFields(){ $fafn = array(); $this->Connexion(); $sql = "SHOW COLUMNS from $this->Table"; $result = $dbh->prepare($sql); $result->execute(); while ($ult = $res->fetch(PDO::FETCH_ASSOC)){ if ($ult['Field'] == 'id') { $rep = $ult['Field']; } else { $fafn[]=$ult['Field'] ; } } return $fafn; } public function insert($values = array()) { $this->Connexion(); $retour = $this->ShowFields(); foreach ($retour as $fil => $val) $index[$val] = '' ; foreach ($values as $field => $v) $ins[] = ':name_' . $field; $ins = implode(',', $ins); $fields = implode(',', array_keys($index)); $sql = "INSERT INTO $this->Table ($fields) VALUES ($ins)"; $sth = $dbh->prepare($sql); foreach ($values as $f => $v) { $sth->bindValue(':name_' . $f, $v); } $sth->execute(); //return $this->lastId = $dbh->lastInsertId(); } }
:?:

Avatar du membre
Administrateur PHPfrance
Administrateur PHPfrance | 9783 Messages

23 déc. 2015, 14:42

Bonjour,
You have an error in your SQL syntax;
Tu as une erreur dans ta requête SQL, fait un echo de celle ci avant de la passer à PDO, ça te permettra de voir ton erreur.
Quand tout le reste a échoué, lisez le mode d'emploi...