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();
}
}