I\'m working on a PHP class method to insert form values into mysql database with PDO. The idea is outlined below but I cannot figure out how to pass in the fourth parameter of
for dynamic insert in PDO i use below function.
for use this passed values in array format to function :
table = strtolower(get_class());
}
public function insert($values = array())
{
$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");
foreach ($values as $field => $v)
$ins[] = ':' . $field;
$ins = implode(',', $ins);
$fields = implode(',', array_keys($values));
$sql = "INSERT INTO $this->table ($fields) VALUES ($ins)";
$sth = $dbh->prepare($sql);
foreach ($values as $f => $v)
{
$sth->bindValue(':' . $f, $v);
}
$sth->execute();
//return $this->lastId = $dbh->lastInsertId();
}
}
and use it :
$contact = new Contact();
$values = array('col1'=>'value1','col2'=>'value2');
$contact->insert($values);