Correction status:Uncorrected
Teacher's comments:
<?php class MyPDO{ private $instance; public function createObj($host="mysql:host=127.0.0.1;dbname=sjzphp", $username="root", $password="root") { $this->instance = new PDO($host, $username, $password); } public function getObj(){ return $this->instance; } public function select($table, $field="*", $where="", $order='', $limit="") { $sql = 'SELECT '.trim($field).' FROM '.trim($table); if (!empty($where) && $where!='') { $sql .= " where ".$where; } if (!empty($order) && $order!='') { $sql .= " order by ".$order; } if (!empty($limit) && $limit!='') { $sql .= " limit ".$limit; } $res = $this->instance->query($sql); //var_dump($res);die; $data = $res->fetchAll(PDO::FETCH_ASSOC); return $data; } public function insert($table, $names, $values) { $sql = "INSERT INTO ".trim($table).'('.$names.') VALUES('.$values.')'; $res = $this->instance->exec($sql); return $res; } public function update($table, $data, $where) { $sql = "UPDATE {$table} SET {$data} WHERE {$where}"; $res = $this->instance->exec($sql); return $res; } public function delete($table, $where){ $sql = "DELETE FROM {$table} WHERE {$where}"; $res = $this->instance->exec($sql); return $res; } } $myPDO = new MyPDO(); $myPDO->createObj(); var_dump($myPDO->select("`user`"));//查询所有数据 //var_dump($myPDO->insert('`user`', '`username`,`password`,`sex`,`age`',"'java', '123456', 1, 18"));//新增一条数据 //var_dump($myPDO->update("`user`", "`username`='PHP'", "`id`=4"));//修改一条数据 //var_dump($myPDO->delete('`user`', '`id`=4'));//删除一条数据
自己模拟一个PDO类,调用里面的方法就能简单的进行增删查改操作。