PHP PDO插入方法

dot*_*cks 4 php pdo insert

我正在研究一个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
    )
    // ------------------------------------------
);
Run Code Online (Sandbox Code Playgroud)

Sae*_* M. 12

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

}
Run Code Online (Sandbox Code Playgroud)

并使用它:

$contact = new Contact();
$values = array('col1'=>'value1','col2'=>'value2');
$contact->insert($values);
Run Code Online (Sandbox Code Playgroud)

  • 他没有使用准备好的陈述,而是使用老式的连接. (2认同)