phpPDO添加数据模型方法

<?php
class PdoModel{

protected $pdoOb="";
function __construct(){

$this->pdoOb = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME."", "".DB_USERNAME."", "".DB_PASSWORD."");
$this->pdoOb -> exec("set names ".DB_CHARSET."");
}
function add($arr){
//拼sql语句
$kArr=array_keys($arr);  //接收数组转化成键名数组
$kStr=join(",",$kArr);   //键值数组转化成字符串
$vArr=array_values($arr);//接收数组转化成键值数组

$pStr = '';
foreach ($vArr as $s=>$y){ //遍历
$vname = "p".$s;       //形成p0,p1...
$pStr.=':'.$vname.','; //形成:p0,:p2,:p3,
}
$pStr = substr($pStr,0,-1);//截掉最后的,
$sql = "insert into {$this->tableName}($kStr) values($pStr)";
    $pdoS = $this->pdoOb ->prepare($sql);//装载
    foreach ($vArr as $k=>$y){//遍历
    $vname = "p".$k;    
    $$vname = $y; //变量函数
    $pdoS -> bindParam(":".$vname, $$vname,PDO::PARAM_STR);//绑定
   
    }
    $re = $pdoS -> execute();
    var_dump($re);

}
}

你可能感兴趣的:(PHP)