摘要:<?phpheader ('content-type:text/html;charset=utf-8');//创建pdo连接数据库$pdo = new PDO('mysql:host=127.0.0.1;dbname=stu','root','root');//创建sql$sql ="INSERT INTO `user`
header('content-type:text/html;charset=utf-8');
//创建pdo连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=stu','root','root');
//创建sql
$sql ="INSERT INTO `user` (`username`,`sex`,`age`,`email`,`status`) VALUES (:username,:sex,:age,:email,:status)";
//3.验证sql语句创建预处理对象stmt
$stmt = $pdo->prepare($sql);
//参数绑定
$username = '沙迦';
$sex = '男';
$age = 25;
$email = 'sj@qq.com';
$status = -1;
$stmt->bindParam(':username',$username,PDO::PARAM_STR,20);
$stmt->bindParam(':sex',$sex,PDO::PARAM_STR,4);
$stmt->bindParam(':age',$age,PDO::PARAM_INT);
$stmt->bindParam(':email',$email,PDO::PARAM_STR,50);
$stmt->bindParam(':status',$status,PDO::PARAM_STR ,4);
if($stmt->execute()){
echo ($stmt->rowCount()>0) ? '成功添加了'.$rowCount().' 条记录' : '没有记录';
}else{
exit(print_r($stmt->errorInfo(),true));
};
?>
header('content-type:text/html;charset=utf-8');
/**
* Created by PhpStorm.
* User: guanzhiyu
* Date: 2019/4/9
* Time: 15:53
* 八、PDO更新操作
* rowCount()方法:返回受影响的记录数量
* errorInfo():返回出错信息(数组格式)
*/
//创建pdo链接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=stu','root','root');
//创建sql;
$sql = "UPDATE `user` SET `email`=:email WHERE `id` = :user_id";
//创建预处理对象
$stmt = $pdo->prepare($sql);
//4参数绑定
$id = 4;
$email = 's@qq.com';
$stmt->bindParam(':user_id',$id ,PDO::PARAM_INT);
$stmt->bindParam(':email',$email,PDO::PARAM_STR,40);
if($stmt->execute()){
echo ($stmt->rowCount()>0) ? '成功更新了' . $stmt->rowCount() .'条数据' : '没有更新记录';
}else{
exit(print_r($stmt->errorInfo(),true));
}
header('content-type:text/html;charset=utf-8');
/**
* Created by PhpStorm.
* User: guanzhiyu
* Date: 2019/4/9
* Time: 19:33
* 九、PDO删除操作
* 删除操作是最微信的写操作;
* 在实际开发过程,我们都是使用软删除实现;
* 软删除就是利用更新模拟删除操作,通过删除标记字段来解决;
* 删除操作,必须基于条件,绝对禁止无条件删除;
* 如果想清空表中数据,请使用:TRUNCATE TABLE 命令;
*/
//创建pdo链接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=stu','root','root');
//创建sql;
$sql = "DELETE FROM `user` WHERE `id` = :user_id";
//创建预处理对象
$stmt = $pdo->prepare($sql);
//4参数绑定
$id = 4;
$email = 's@qq.com';
$stmt->bindParam(':user_id',$id ,PDO::PARAM_INT);
if($stmt->execute()){
echo ($stmt->rowCount()>0) ? '成功删除了' . $stmt->rowCount() .'条数据' : '没有记录被删除';
}else{
exit(print_r($stmt->errorInfo(),true));
}
批改老师:天蓬老师批改时间:2019-04-10 09:41:25
老师总结:删除操作, 是最危险的操作之下, 而且是物理删除,所以必须要有条件, 要当心