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的数据 */
  • 相关阅读:
    (4.7)怎么捕获和记录SQL Server中发生的死锁?
    SQLSERVER排查CPU占用高的情况
    (4.6)sql server索引缺失提示
    (4.14)向上取整、向下取整、四舍五入取整的实例
    mysql大致学习路径
    (2)linux未使用eth0,未使用IPV4导致无法连接
    (4.13)sql server参数嗅探(parameter sniffing)
    完美女人
    关于box-sizing
    什么是担当
  • 原文地址:https://www.cnblogs.com/GetcharZp/p/12177425.html
Copyright © 2011-2022 走看看