PHP PDO插入方法


PHP PDO Insert Method

我正在开发一种PHP类方法,用PDO将表单值插入mysql数据库。这个想法概述如下,但我不知道如何传入该方法的第四个参数。有人能解释一下怎么做吗?

谢谢!

<?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
    )
    // ------------------------------------------
);
对于PDO中的动态插入,我使用以下函数。

用于使用数组格式中传递的值来执行以下操作:

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

并使用它:

$contact = new Contact();
$values = array('col1'=>'value1','col2'=>'value2');
$contact->insert($values);

我会使用一个数组。也许是这样的:

public function MySqlDbInsert($DbTableName, $values = array())
{
    try{
        $dbh = new PDO('.....');
        // Specify the tables where you can insert
        $allowedTables = array('table_1', 'table_2', 'table_3');
        // Specify allowed column names
        $allowedColumns = array('age', 'city', 'address');
        if (!in_array($DbTableName, $allowedTables))
            throw new Exception('Invalid Table Given!');
        $columns = array_keys($values);
        foreach ($columns as $c)
        {
            if (!in_array($c, $allowedColumns))
                throw new Exception('The column ' . $c. ' is not allowed');
        }
        $sql = 'INSERT INTO ' . $DbTableName;
        $sql .= '(' . implode(',', $columns) . ') ';
        $sql .= 'VALUES (' . implode(',', array_fill(0, count($values), '?')) . ')';
        $sth = $dbh->prepare($sql);
        $sth->execute(array_values($values));
    }
    catch(PDOException $e){
        $this->ResponseMessage(true, 'Database access FAILED!');
    }
    catch(Exception $e) { $this->ResponseMessage(true, $e->getMessage()); }
}
$contact->MySqlDbInsert('table_name', array('colname1' => 'value1', 'colname2' => 'value2', 'colname3' => 'value3'));

不过,所有值都将转义为"PDO::PARAM_STR"。

我的INSERT函数

function basicInsertQuery($tableName,$values = array()){
/*
//
USAGE INSERT FUNCTİON
    $values = [
        "column" => $value,               
    ];
    $result =  basicInsertQuery("bulk_operations",$values);
*/
try {
    global $pdo;
    foreach ($values as $field => $v)
        $vals[] = ':' . $field;
    $ins = implode(',', $vals);
    $fields = implode(',', array_keys($values));
    $sql = "INSERT INTO $tableName ($fields) VALUES ($vals)";
    $rows = $pdo->prepare($sql);
    foreach ($values as $k => $vl)
    {
        $rows->bindValue(':' . $k, $l);
    }
    $result = $rows->execute();
    return $result;
} catch ('Throwable $th) {
   return $th;
}

}