PDO预处理对数据的增删查改

编辑: admin 分类: 电脑知识 发布时间: 2023-06-14 来源:互联网
PDO预处理对数据的增删查改1.增
  1. $sql = "INSERT INTO T_product (proid,proname,price,description) VALUES (?,?,?,?)";
  2. // 预处理要执行的语句
  3. $stmt = $dbh->prepare($sql);
  4. $proid = '120019';
  5. $proname = '笔记本';
  6. $price = 12800;
  7. $description = '华硕笔记本,高配置';
  8. $flag = $stmt->execute([$proid,$proname,$price,$description]);
  9. if($flag){
  10. echo '添加成功'.$dbh->lastInsertId();
  11. }else{
  12. echo '添加失败';
  13. die();
  14. }
2. 删除
  1. <?php
  2. //预处理sql语句
  3. $sql = 'DELETE from T_product WHERE id=?';
  4. //准备要执行的语句
  5. $stmt = $dbh->prepare($sql);
  6. $delid = 2;
  7. $flag= $stmt->execute([$delid]);
  8. if($flag){
  9. echo '删除成功';
  10. }else{
  11. echo '删除失败';
  12. die(;)
  13. }
3. 查
  1. $sql = 'SELECT * FROM T_product WHERE id>?';
  2. $stmt = $dbh->prepare($sql);
  3. $selectid = 1;
  4. $stmt->execute([$selectid]);
  5. $res = $stmt->fetchAll();
  6. if ($res){
  7. print_r($res);
  8. }else{
  9. die('查询失败');
  10. }
4. 改
  1. $sql = 'UPDATE T_product SET proid=?,proname=?,price=? WHERE id=?';
  2. $stmt = $dbh->prepare($sql);
  3. $proid = '120016';
  4. $proname = '手机';
  5. $price = 2600;
  6. $updateid=1;
  7. $flag = $stmt->execute([$proid,$proname,$price,$updateid]);
  8. if($flag){
  9. echo '更新成功';
  10. }else{
  11. die('更新失败');
  12. }
【文章转自中东服务器 http://www.558idc.com/dibai.html欢迎留下您的宝贵建议】