abstract:数据库名 test CREATE TABLE `user` ( `uid` INT(11) NOT NULL AUTO_INCREMENT, `uname` VARCHAR(10) NOT NULL, `sex`&nb
数据库名 test CREATE TABLE `user` ( `uid` INT(11) NOT NULL AUTO_INCREMENT, `uname` VARCHAR(10) NOT NULL, `sex` VARCHAR(30) NOT NULL DEFAULT '男', PRIMARY KEY (`uid`) ) ENGINE=MYISAM AUTO_INCREMENT=13 DEFAULT CHARSET=utf8
连接
$type = 'mysql'; $host = '127.0.0.1'; $dbname = 'test'; $charset = 'utf8';
$dns = $type.':host='.$host.';dbname='.$dbname.';charset='.$charset; try{ $pdo = new PDO($dns,'root','root'); }catch (PDOException $e){ echo $e->getMessage(); }
新增
$sql='INSERT INTO `user` (`uname`,`sex`) VALUES (:uname,:sex)'; //创建预处理对象 $stmt=$pdo->prepare($sql); //参数绑定 $usex='男'; $uname='mrhaha'; $stmt->bindParam(':uname',$uname,PDO::PARAM_STR,10); $stmt->bindParam(':sex',$usex,PDO::PARAM_STR,5); if($stmt->execute()){ echo ($stmt->rowCount()>0) ? '成功添加了'.$stmt->rowCount().'条数据' : '添加失败'; }else{ exit(print_r($stmt->errorInfo(),true)); }
修改
$sql='UPDATE `user` SET `uname`=:uname,`sex`=:sex where uid = :id'; //创建预处理对象 $stmt=$pdo->prepare($sql); //参数绑定 $id=2; $usex='女'; $uname='mr666'; $stmt->bindParam(':uname',$uname,PDO::PARAM_STR,10); $stmt->bindParam(':sex',$usex,PDO::PARAM_STR,5); $stmt->bindParam(':id',$id,PDO::PARAM_INT); if($stmt->execute()){ echo ($stmt->rowCount()>0) ? '成功修改了'.$stmt->rowCount().'条数据' : '修改失败'; }else{ exit(print_r($stmt->errorInfo(),true)); }
删除
$sql='DELETE FROM `user` where uid = :id'; //创建预处理对象 $stmt=$pdo->prepare($sql); //参数绑定 $stmt->bindValue(':id',2,PDO::PARAM_INT); //执行 if($stmt->execute()){ echo ($stmt->rowCount()>0) ? '成功刪除了'.$stmt->rowCount().'条数据' : '刪除失败'; }else{ exit(print_r($stmt->errorInfo(),true)); }
释放结果集
$stmt=null;
关闭连接
$pdo=null;
Correcting teacher:查无此人Correction time:2019-02-18 09:16:59
Teacher's summary:完成的不错,数据库操作现在都用pdo了,要多练习,继续加油。