返回 PDO的新增,...... 登陆

PDO的新增,更新,删除操作

连界 现代 周伟 2019-06-11 23:14:50 267

<?php
//pdo中的新增操作
//1.创建pdo对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
//2.创建SQL语句
$sql = "INSERT INTO `staff` (`name`,`age`,`sex`,`position`,`mobile`,`hiredate`,`is_show`) VALUES (:name,:age,:sex,:position,:mobile,:hiredate,:is_show)";
//3.创建预处理对象
$stmt = $pdo->prepare($sql);
//4.参数绑定
$name = '张三';
$age = 25;
$sex =1;
$position = '经理';
$mobile = '13311112222';
$hiredate = time();
$isShow = 1;
$stmt->bindParam(':name',$name,PDO::PARAM_STR,20);
$stmt->bindParam(':age',$age,PDO::PARAM_INT);
$stmt->bindParam(':sex',$sex,PDO::PARAM_INT);
$stmt->bindParam(':position',$position,PDO::PARAM_STR,30);
$stmt->bindParam(':mobile',$mobile,PDO::PARAM_STR,11);
$stmt->bindParam(':hiredate',$hiredate,PDO::PARAM_INT);
$stmt->bindParam(':is_show',$isShow,PDO::PARAM_INT);

//5.执行添加
if($stmt->execute()){
   echo ($stmt->rowCount()>0) ? '成功添加了 ' . $stmt->rowCount() . ' 条记录!' : '没有记录被添加';
}else {
   exit(print_r($stmt->errorInfo(),true));
}


<?php
//pdo中的更新操作
//1.创建pdo对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
//2.创建SQL语句
$sql = "UPDATE `staff` SET `age` = :age,`position` = :position,`mobile` = :mobile WHERE `id` = :id";
//3.创建预处理对象
$stmt = $pdo->prepare($sql);
//4.参数绑定
$id = 43;
$age = 28;
$position = '总经理';
$mobile = '13311113333';

$stmt->bindParam(':age',$age,PDO::PARAM_INT);
$stmt->bindParam(':id',$id,PDO::PARAM_INT);
$stmt->bindParam(':position',$position,PDO::PARAM_STR,30);
$stmt->bindParam(':mobile',$mobile,PDO::PARAM_STR,11);

//5.执行更新
if($stmt->execute()){
   echo ($stmt->rowCount()>0) ? '成功更新了 ' . $stmt->rowCount() . ' 条记录!' : '没有记录被更新';
}else {
   exit(print_r($stmt->errorInfo(),true));
}

<?php
//pdo中的删除操作
//1.创建pdo对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
//2.创建SQL语句
$sql = "DELETE FROM `staff` WHERE `id` = :id";
//3.创建预处理对象
$stmt = $pdo->prepare($sql);
//4.参数绑定
$id = 38;
$stmt->bindParam(':id',$id,PDO::PARAM_INT);
//5.执行删除
if($stmt->execute()){
   echo ($stmt->rowCount()>0) ? '成功删除了 ' . $stmt->rowCount() . ' 条记录!' : '没有记录被删除';
}else {
   exit(print_r($stmt->errorInfo(),true));
}

最新手记推荐

• 用composer安装thinkphp框架的步骤 • 省市区接口说明 • 用thinkphp,后台新增栏目 • 管理员添加编辑删除 • 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消 回复 发送
  • PHP中文网