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 the method. Could someone explain how to do this?
Thank you!
<?php
class Contact {
private $DbHost = DB_HOST;
private $DbName = DB_NAME;
private $DbUser = DB_USER;
private $DbPass = DB_PASS;
public function MySqlDbInsert($DbTableName, $DbColNames, $DbValues, $DbBindParams){
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");
$sth = $dbh->prepare("INSERT INTO $DbTableName($DbColNames) VALUES ($DbValues)");
// i know this is all wrong ----------------
foreach($DbBindParams as $paramValue){
$sth->bindParam($paramValue);
}
// ----------------------------------------
$sth->execute();
}
catch(PDOException $e){
$this->ResponseMessage(true, 'Database access FAILED!');
}
}
$object = new Contact();
$object->MySqlDbInsert(
'DbTableName',
'DbColName1, DbColName3, DbColName3',
':DbColValue1, :DbColValue2, :DbColValue3',
// this part is all wrong -------------------
array(
':DbColValue1', $col1, PDO::PARAM_STR,
':DbColValue2', $col2, PDO::PARAM_STR,
':DbColValue2', $col3, PDO::PARAM_STR
)
// ------------------------------------------
);
for dynamic insert in PDO i use below function.
for use this passed values in array format to function :
<?php
class Contact
{
private $UploadedFiles = '';
private $DbHost = DB_HOST;
private $DbName = DB_NAME;
private $DbUser = DB_USER;
private $DbPass = DB_PASS;
private $table;
function __construct()
{
$this->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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With