Monday, 28 May 2018

PHP PDO Insert Method

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

}

No comments:

Post a Comment