玩一下php的pdo操作

pdo模块,实际是php data object php数据对象
默认php.ini里面是开着的
首先php用来操作数据库的一共有3大类

  1. pdo类
  2. 预处理类
  3. 异常处理类

在写一个简单小模块中先熟悉一下pdo类下面的这些操作方法

  1. 连接pdo数据库
//dsn 数据源名称
$dsn  ="mysql:host=localhost;dbname=www.hm.com";
//数据库名称
$username = "hmcom";
//数据库密码
$password = "123456";
//pdo对象
$pdo = new PDO($dsn,$username,$password);
//设置字符集
//exec()执行一条sql 并返回条数,用于增删改 查用query()
$pdo->exec('set names utf8');
//设置属性
$pdo->setAttribute();

这样一来数据库就连接上了,搞点小例子吧
随便搞一个表实现用户简单的增删改查
随便搞一个user表

  1. config.php
//因为增删改查都需要调用数据库
//就姑且放到这里用的时候引用一下就好
$dsn = "mysql:host=localhost;dbname=www.hm.com";
$username = "hmcom";
$password = "123456";
$pdo = new PDO($dsn,$username,$password);
$pdo->exec('set names utf8');
  1. index.php 列表页面
<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/12/24
 * Time: 9:51
 */
//用户模块开发
include 'config.php';
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
//这里可加可不加,加了统一设置,不加就写的时候设置
//这个是异常的时候,可以展示异常的信息,如果不写的话getMessage()就显示不出来
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

$sql = "select * from `user` ";
//返回预处理对象
$smt = $pdo->prepare($sql);
//执行预处理语句 bool值
$smt->execute();
//查询并得到数据集合
//其实也可以这样
//if($smt->execute()){
    
    
//$result  =  $smt -> fetchAll();
//}
//不过看手册好像也没这么弄
$result  =  $smt -> fetchAll();

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <!-- JS, Popper.js, and jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <style>
        td.th{
    
    
            vertical-align: middle !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 class="page-header">
           用户管理
        </h2>
        <table class="table table-striped table-bordered">
            <tr>
                <th>编号</th>
                <th>用户名</th>
                <th>密码</th>
                <th>修改</th>
                <th>删除</th>
            </tr>
            <?
                foreach ($result as $row){
    
    
                    echo "<tr>";
                        echo "<td>{
      
      $row['id']}</td>";
                        echo "<td>{
      
      $row['name']}</td>";
                        echo "<td>{
      
      $row['money']}</td>";
                        echo "<td><a class='btn btn-warning' href='model.php?id={
      
      $row['id']}'>修改</a></td>";
                        echo "<td><a class='btn btn-danger' href='del.php?id={
      
      $row['id']}'>删除</a></td>";
                    echo "</tr>";
                }
            ?>
        </table>
        <p >
            <a class="btn btn-success btn-primary btn-large" href="add.php">添加用户</a>
        </p>
    </div>
</body>
</html>

//这个是异常的时候,可以展示异常的信息,如果不写的话getMessage()就显示不出来
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
如图列表页面

  1. del.php 删除页面
<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/12/24
 * Time: 14:23
 */

include "config.php";
$id = $_GET['id'];
//用了下事务机制 想想打钱就知道了
//事务是多个sql执行的时候, 如果都成功则执行成功,事件结束,如果其中有一个失败,则回滚,事件最终也会结束
//开启事务
$pdo->beginTransaction();
//事务一般跟异常处理放在一起哟
try{
    
    
    $sql = "delete from `user` where id = ?";
    //返回一个预处理对象
    $smt = $pdo->prepare($sql);
    //把一个值绑定到一个参数 
    $smt->bindValue(1,$id,PDO::PARAM_INT);
//    $smt->execute();这里返回的是bool值 执行预处理语句
    if($smt->execute()){
    
    
        echo '<script>alert("删除成功");location="index.php"</script>';
    }
    //成功提交并结束事务
    $pdo->commit();
}catch (PDOException $pdoex){
    
    
    $pdoex->getMessage();//得到异常位置的信息
    $pdoex->getCode();//得到异常位置的code值
    $pdoex->getLine();//得到异常位置的行数
    //失败回滚并结束事务
    $pdo->rollback();
}
  1. 修改页面
<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/12/24
 * Time: 14:38
 */

include "config.php";
if(empty($_POST)){
    
    
    $id = $_GET['id'];
    echo $id;
    $sql = "select * from `user` where id = ? ";
    $smt = $pdo->prepare($sql);
    $smt->bindValue(1,$id,PDO::PARAM_INT);
//执行预处理语句
    $smt->execute();
//成功了的话,开始操作后面的
    $result  =  $smt -> fetchAll();
    foreach ($result as $row){
    
    
        $name = $row['name'];
        $money = $row['money'];
    }
}else{
    
    
    $id = $_POST['id'];
    $name = $_POST['name'];
    $money = $_POST['money'];
    $sql = "update `user` set name='$name',money='$money' where id = $id ";
    $smt = $pdo->prepare($sql);
    if($smt->execute()){
    
    
        echo '<script>alert("修改成功");</script>';
        echo "<script>location='index.php'</script>";
    }else{
    
    
        echo '修改失败';
    }
}

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h2 class="page-header">
    用户管理
</h2>
<form action="" method="post" enctype="multipart/form-data">
    <input type="text" name="name" value="<?=$name?>">
    <input type="text" name="money" value="<?=$money?>">
    <input type="hidden" name="id" value="<?=$id?>">
    <input type="submit" value="提交">
</form>
    
</body>
</html>

忘记写样式了就没写样式了

  1. 增加页面
<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/12/24
 * Time: 14:38
 */

include "config.php";
if(empty($_POST)){
    
    
//    echo '请重新提交';
}else{
    
    
    $name = $_POST['name'];
    $money = $_POST['money'];
    $sql = "insert into `user`(name,money) value('{
      
      $name}',$money)";
    $smt = $pdo->prepare($sql);
    if($smt->execute()){
    
    
    	//这里得到影响的行数
        $num = $smt->rowCount();
        echo "<script>alert('新增'+$num+'条数据');location='index.php'</script>";
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <!-- JS, Popper.js, and jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
    <h2 class="page-header">
        用户管理
    </h2>
    <form action="add.php" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="">用户名:</label>
            <input type="text" class="form-control" name="name" value="" placeholder="请输入用户名">
        </div>
        <div class="form-group">
            <label for="">密码:</label>
            <input type="text" class="form-control" name="money" value="" placeholder="请输入密码">
        </div>
        <input class="btn btn-primary btn-success" type="submit" value="提交">
    </form>
</div>

</body>
</html>

页面比较丑如果有不足或者写错的地方欢迎大佬们指点指点谢谢。

猜你喜欢

转载自blog.csdn.net/weixin_44088587/article/details/111633486