zoukankan      html  css  js  c++  java
  • 通过 PDO 实现简单的 CRUD

    数据库表的准备 user

    CREATE TABLE `user` (
      `id` int(11) NOT NULL,
      `name` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
    INSERT INTO `tp6`.`user` (`id`, `name`) VALUES ('1', 'Getcharzp');
    INSERT INTO `tp6`.`user` (`id`, `name`) VALUES ('5', 'GetcharZp');
    INSERT INTO `tp6`.`user` (`id`, `name`) VALUES ('3', 'MCX');

    PDO

    主要函数说明:

    prepare();  // 预处理函数,它的参数为 SQL 语句
    execute();  // 用来执行预处理函数中的 SQL 语句,它的参数为 SQL 语句中所对应的变量
    fetch();   // 返回一条结果
    fetchAll(); // 返回多条结果

    首先,要连接数据库

    $host = "localhost";
    $db = "tp6";
    $charset = "utf8mb4";
    $username = "root";
    $password = "root";
    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $conn = new PDO($dsn, $username, $password);

    然后,我们来看下相关的 CRUD 操作

    一、查询一条结果

    $select = $conn->prepare("select * from user");
    $select->execute();
    $res = $select->fetch();
    var_dump($res);

    二、查询所有结果

    $select = $conn->prepare("select * from user");
    $select->execute();
    $res = $select->fetchAll();
    var_dump($res);

    三、带条件的查询,主要是 prepare 准备坑位,execute 填补坑位

    // 查询 name 为 GetcharZP 的所有数据
    $select = $conn->prepare("select * from user where name = :name");
    $select->execute(array(":name" => "GetcharZP"));
    $res = $select->fetchAll();
    var_dump($res);

    四、增加数据

    $insert = $conn->prepare("insert into user(id, name) values(:id, :name)");
    $insert->execute(array(':id' => 6, ':name' => 'GetcharMcx'));

    五、修改数据

    $update = $conn->prepare("update user set name = :name where id = :id");
    $update->execute(array(":name" => "A-zero", ":id" => 3));

    六、删除数据

    $delete = $conn->prepare("delete from user where id = :id");
    $delete->execute(array(':id' => 6));    /* 删除ID为6的数据 */
  • 相关阅读:
    [NOI2004] 郁闷的出纳员
    [洛谷P4556] 雨天的尾巴
    【转】进程、线程、 GIL全局解释器锁知识点整理
    Python3中的SocketServer
    socket 上传文件代码
    python socket 连续send,出现粘包问题
    【转】动态导入模块的两种方法
    【转】面向对象高级语法部分
    python的垃圾回收机制和析构函数__del__
    django 项目使用setting文件里定义的变量方法
  • 原文地址:https://www.cnblogs.com/GetcharZp/p/12177425.html
Copyright © 2011-2022 走看看