封裝一個PDO操作mysql的類
阿新 • • 發佈:2018-12-10
class PdoMiao{ protected $config=array( 'host'=>'localhost', 'database'=>'', 'hostport'=>'3306', 'charset'=>'utf-8' ); protected $dsn=null; protected $user='root'; protected $passwd='root'; public function __construct($config){ $dsn=$this->parseDsn($this->config); try{ $this->dsn=new \PDO($dsn,$this->user,$this->passwd); }catch(\PDOException $e){ echo "連線失敗:"$e->getMessage(); } $this->host=$config['host']; $this->user=$config['user']; $this->passwd=$config['passwd']; $this->charset=$config['charset']; $this->database=$config['database']; } public function parseDsn($config){ $dsn="mysql:host=".$config['host'].";dbname=".$config['database']; if(!empty($config['port'])){ $dsn.=";port=".$config['port']; } if(!empty($config['charset'])){ $dsn.=";charset=".$config['charset']; } return $dsn; } public function insert($datas){ $sql="insert into `miaosha`( `id` ,`phone` ,`number`) values(null,?,?,?)" ; $sth=$this->dsn->prepare($sql); foreach($datas as $k=>$v){ $sth->execute($v); } } }