Blogger Information
Blog 28
fans 0
comment 0
visits 16763
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
mysqli 面向对象实现更新和 PDO 实现删除-2018年05月01日00:30
植树青年小江同志的博客
Original
482 people have browsed it

面向对象的方式来实现更新操作

实例

<?php

// 连接数据库
require 'mysqli_connect.php';

// 准备 SQL 语句
$sql = "UPDATE staff SET salary = ? WHERE staff_id = ?;";

// 创建 STMT 预处理对象
$stmt = $mysqli->smtmt_init();

// 检测预处理 SQL 语句
if ($stmt->prepare($sql)) {
  // 绑定参数到预处理 SQL 语句
  $stmt->bind_param('ii', $salary, $staff_id);

  // 设置参数
  $salary = 7555;
  $staff_id = 3;

  // 执行预处理语句

  $stmt->execute();
  if ($stmt->affected_rows > 0) {
    echo '<br>成功更新'.$stmt->affected_rows.'条记录';
  } else {
    echo '<br>没有更新记录';
  }

  // 注销 stmt 对象
  $stmt->close();
} else {
  exit($stmt->error . ':' . $stmt->error);
}

// 关闭数据库连接
$mysqli->close();

运行实例 »

点击 "运行实例" 按钮查看在线实例


PDO 实现数据库删除

实例

<?php


// 连接数据库
try {
  $connect = new PDO('mysql:dbname=php','gakkispy', 'password');
} catch (PDOException $err) {
  exit($err->getMessage());
}

// 准备 SQL 语句
$sql = "DELETE FROM staff WHERE staff_id=:staff_id;";

// 创建 stmt 预处理对象
if ($stmt = $connect->prepare($sql)) {
  //  绑定参数 stmt 对象

  // 参数
  $param = ['staff_id'=>9];

  // 绑定参数到预处理 SQL 语句

  if ($stmt -> execute($param)) {
    // rowCount() 返回执行的数量
    if ($stmt->rowCount()>0) {
      echo '成功删除了'.$stmt->rowCount().'条记录';
    } else {
      echo '没有记录被删除';
    }
  } else {
    // 失败
    print_r($stmt->errorInfo());
  }
} else {
  // $stmt s语句对象创建失败
  print_r($connect->errorInfo());
  exit();
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post