Blogger Information
Blog 51
fans 3
comment 1
visits 36237
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
MySQLi面向对象实现更新操作 PDO实现删除操作—2018年4月25日22时30分
Gee的博客
Original
568 people have browsed it

MySQLi面向对象实现更新操作:

实例

<?php
/**
 * 面向对象实现更新操作
 */

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

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

//3.创建出预处理对象STMT
$stmt = $mysqli->stmt_init();

//4.检测STMT,预处理的SQL语句对象
if($stmt->prepare($sql)) {
    //创建二维数组来保存要添加的数据
    $data[] = ['salary'=>'6666', 'staff_id'=>'6'];
    $data[] = ['salary'=>'7777', 'staff_id'=>'7'];

    //绑定参数
    $stmt->bind_param('ii',$salary,$staff_id);
    //5.执行SQL语句
    foreach ($data as $staff) {
        $salary = $staff['salary'];
        $staff_id = $staff['staff_id'];
        $stmt->execute();

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

} else {
    exit($stmt->errno.':'.$stmt->error);
}

//6.关闭连接
$mysqli->close();

运行实例 »

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

PDO实现删除操作:

实例

<?php
/**
 * 预处理删除数据
 */

//1.连接数据库,创建pdo对象
$pdo = new PDO('mysql:dbname=php','root','root');

//2.创建预处理语句对象
$stmt = $pdo->prepare("DELETE FROM user WHERE user_id=:user_id");

//3.将参数绑定到预处理语句对象并执行
$stmt -> execute(['user_id'=>5]);

echo '成功删除了'.$stmt->rowCount().'条记录';

运行实例 »

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

总结:

    需要注意PDO中准备sql语句部分

    例如:$sql = "INSERT `user` SET `user_name`=:name ,`email`=:email, `password`=sha1(:password) ";

    变量前需要加冒号,用的“ ` ”不是单引号 “ ’”

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