Blogger Information
Blog 48
fans 2
comment 3
visits 37860
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
4月25日作业—面向对象更新操作和PDO实现删除操作
黑猫警长的博客
Original
600 people have browsed it

预处理的更操作

<?php

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

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

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

//4.检测预处理SQL语句
if ($stmt->prepare($sql)) {

    //用二维数组来保存要添加的记录
    $data[] = ['name'=> '王重阳','salary'=>9000,'staff_id'=>24];

    //绑定参数到预处理SQL语句
    $stmt->bind_param('sii',$name,$salary,$staff_id);

    foreach ($data as $staff) {
        //准备要更新的数据
        $name = $staff['name'];
        $salary = $staff['salary'];
        $staff_id = $staff['staff_id'];
        //执行预处理语句
        $stmt->execute();
        //检测运行结果
        if ($stmt->affected_rows > 0 ){
            echo '<br>成功更新'.$stmt->affected_rows.'条记录';
        } else {
            echo '<br>没有记录被更新';
        }
    }

    //5.注销stmt对象
    $stmt->close();
} else {  //返回错误信息
    exit($stmt->errno.':'.$stmt->error);
}


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

运行实例 »

PDO实现删除操作

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

//1.连接数据库,创建pdo对象
try {
$pdo = new PDO('mysql:dbname=php','root','root');
} catch (PDOException $e) {
    exit($e->getMessage());
}

//2.准备sql语句
// DELETE FROM user WHERE user_id = 12 
$sql = "DELETE FROM user WHERE user_id=:user_id";

//3.创建预处理对象stmt对象
if($stmt = $pdo->prepare($sql)) {

    //4.将参数绑定到stmt对象并执行
    //准备参数
    $param = ['user_id'=>12];

    //绑定参数到SQL语句对象并执行
    if ($stmt -> execute($param)){
        //rowCount()返回更新的数量,如果大于0表示有记录被删除
        if ($stmt->rowCount()>0) {
            echo '成功删除了'.$stmt->rowCount().'条记录';
        } else {  //等于0表示没有记录被删除
            echo '没有记录被删除';
        }
    } else { //执行失败的信息
        print_r($stmt->errorInfo());
        exit();
    }

} else {  //$stmt语句对象创建失败
  print_r($pdo->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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!