一、连接MYSQL

  1.1 MySQLi - 面向对象

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    // 创建连接
    $conn = new mysqli($servername, $username, $password);
    // 检测连接
    if ($conn->connect_error) {
      die("连接失败: " . $conn->connect_error);
    }
    echo "连接成功";
  ?>
  关闭连接:$conn->close();   1.2 MySQLi - 面向过程

   <?php
     $servername = "localhost";
     $username = "username";
     $password = "password";

      // 创建连接
      $conn = mysqli_connect($servername, $username, $password);

     // 检测连接
     if (!$conn) {
       die("Connection failed: " . mysqli_connect_error());
     }
     echo "连接成功";
   ?>

  关闭连接:mysqli_close($conn);

   1.3 PDO 

   <?php
     $servername = "localhost";
     $username = "username";
     $password = "password";

     try {
       $conn = new PDO("mysql:host=$servername;", $username, $password);
       echo "连接成功";
     }
     catch(PDOException $e)
     {
       echo $e->getMessage();
     }
   ?>

   关闭连接:$conn = null;   

 二、创建数据库

  2.1 MySQLI - 面向对象 

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";

    // 创建连接
    $conn = new mysqli($servername, $username, $password);
    // 检测连接
    if ($conn->connect_error) {
      die("连接失败: " . $conn->connect_error);
    }

    // 创建数据库
    $sql = "CREATE DATABASE myDB";
    if ($conn->query($sql) === TRUE) {
      echo "数据库创建成功";
    } else {
      echo "Error creating database: " . $conn->error;
    }

    $conn->close();
  ?>

  2.2 MySQLi - 面向过程

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";

    // 创建连接
    $conn = mysqli_connect($servername, $username, $password);
    // 检测连接
    if (!$conn) {
      die("连接失败: " . mysqli_connect_error());
    }

    // 创建数据库
    $sql = "CREATE DATABASE myDB";
    if (mysqli_query($conn, $sql)) {
      echo "数据库创建成功";
    } else {
      echo "Error creating database: " . mysqli_error($conn);
    }

    mysqli_close($conn);
  ?>

  2.3 PDO 

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";

    try {
      $conn = new PDO("mysql:host=$servername", $username, $password);

      // 设置 PDO 错误模式为异常
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $sql = "CREATE DATABASE myDBPDO";

      // 使用 exec() ,因为没有结果返回
      $conn->exec($sql);

      echo "数据库创建成功<br>";
    }
    catch(PDOException $e)
    {
      echo $sql . "<br>" . $e->getMessage();
    }

    $conn = null;
  ?>

 

 三、创建数据库表 

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDBPDO";

    try {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      // 设置 PDO 错误模式,用于抛出异常
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      // 使用 sql 创建数据表
      $sql = "CREATE TABLE MyGuests (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(30) NOT NULL,
        lastname VARCHAR(30) NOT NULL,
        email VARCHAR(50),
        reg_date TIMESTAMP
      )";

      // 使用 exec() ,没有结果返回
      $conn->exec($sql);
      echo "数据表 MyGuests 创建成功";
    }
    catch(PDOException $e)
    {
      echo $sql . "<br>" . $e->getMessage();
    }

    $conn = null;
  ?>

 四、插入数据

  3.1 MYSQLi - 面向对象 

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // 创建连接
    $conn = new mysqli($servername, $username, $password, $dbname);
    // 检测连接
    if ($conn->connect_error) {
      die("连接失败: " . $conn->connect_error);
    }

    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if ($conn->query($sql) === TRUE) {
      echo "新记录插入成功";
    } else {
      echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
  ?>

  3.2 MySQLi - 面向过程

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // 创建连接
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // 检测连接
    if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if (mysqli_query($conn, $sql)) {
      echo "新记录插入成功";
    } else {
      echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

    mysqli_close($conn);
  ?>

  3.3 PDO 

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDBPDO";

    try {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      // 设置 PDO 错误模式,用于抛出异常
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $sql = "INSERT INTO MyGuests (firstname, lastname, email)
      VALUES ('John', 'Doe', 'john@example.com')";
      // 使用 exec() ,没有结果返回
      $conn->exec($sql);
      echo "新记录插入成功";
    }
    catch(PDOException $e)
    {
      echo $sql . "<br>" . $e->getMessage();
    }

    $conn = null;
  ?>

 五、插入多条数据

  5.1 PDO

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDBPDO";

    try {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      // set the PDO error mode to exception
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      // 开始事务
      $conn->beginTransaction();
      // SQL 语句
      $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
      VALUES ('John', 'Doe', 'john@example.com')");
      $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
      VALUES ('Mary', 'Moe', 'mary@example.com')");
      $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
      VALUES ('Julie', 'Dooley', 'julie@example.com')");

      // 提交事务
      $conn->commit();
      echo "新记录插入成功";
    }
    catch(PDOException $e)
    {
      // 如果执行失败回滚
      $conn->rollback();
      echo $sql . "<br>" . $e->getMessage();
    }

    $conn = null;
  ?>

  5.2 使用预处理语句 

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // 创建连接
    $conn = new mysqli($servername, $username, $password, $dbname);
    // 检测连接
    if ($conn->connect_error) {
      die("连接失败: " . $conn->connect_error);
    } else {
      $sql = "INSERT INTO MyGuests(firstname, lastname, email) VALUES(?, ?, ?)";

      // 为 mysqli_stmt_prepare() 初始化 statement 对象
      $stmt = mysqli_stmt_init($conn);

      //预处理语句
      if (mysqli_stmt_prepare($stmt, $sql)) {
        // 绑定参数
        mysqli_stmt_bind_param($stmt, 'sss', $firstname, $lastname, $email);

        // 设置参数并执行
        $firstname = 'John';
        $lastname = 'Doe';
        $email = 'john@example.com';
        mysqli_stmt_execute($stmt);

        $firstname = 'Mary';
        $lastname = 'Moe';
        $email = 'mary@example.com';
        mysqli_stmt_execute($stmt);

        $firstname = 'Julie';
        $lastname = 'Dooley';
        $email = 'julie@example.com';
        mysqli_stmt_execute($stmt);
      }
    }
  ?>

  注意:函数mysqli_stmt_bind_param()绑定参数查询并将参数传递给数据库第二个参数是"sss",s 字符告诉 mysql 参数是字符串;以下列表展示了参数的类型;

    i - 整数
    d - 双精度浮点数
    s - 字符串
    b - 布尔值

 

 六、读取数据  

  6.1 面向对象 

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // 创建连接
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
      die("连接失败: " . $conn->connect_error);
    }

    $sql = "SELECT id, firstname, lastname FROM MyGuests";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
      // 输出数据
      while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
      }
    } else {
      echo "0 结果";
    }
    $conn->close();
  ?>

  6.2 面向过程

  <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // 创建连接
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
      die("连接失败: " . mysqli_connect_error());
    }

    $sql = "SELECT id, firstname, lastname FROM MyGuests";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
      // 输出数据
      while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
      }
    } else {
      echo "0 结果";
    }

    mysqli_close($conn);
  ?>

  6.3 PDO(使用预处理)

  <?php
    echo "<table style='border: solid 1px black;'>";
    echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

    class TableRows extends RecursiveIteratorIterator {
      function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
      }

      function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
      }

      function beginChildren() {
        echo "<tr>";
      }  

      function endChildren() {
        echo "</tr>" . "\n";
      }
    }

    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDBPDO";

    try {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
      $stmt->execute();

      // 设置结果集为关联数组
      $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
      foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
      }
    }
    catch(PDOException $e) {
      echo "Error: " . $e->getMessage();
    }
    $conn = null;
    echo "</table>";
  ?>

PHP基础学习笔记5的更多相关文章

  1. 【C#编程基础学习笔记】4---Convert类型转换

    2013/7/24 技术qq交流群:JavaDream:251572072  教程下载,在线交流:创梦IT社区:www.credream.com [C#编程基础学习笔记]4---Convert类型转换 ...

  2. 【C#编程基础学习笔记】6---变量的命名

    2013/7/24 技术qq交流群:JavaDream:251572072  教程下载,在线交流:创梦IT社区:www.credream.com [C#编程基础学习笔记]6---变量的命名 ----- ...

  3. 1.C#基础学习笔记3---C#字符串(转义符和内存存储无关)

    技术qq交流群:JavaDream:251572072  教程下载,在线交流:创梦IT社区:www.credream.com ------------------------------------- ...

  4. Java基础学习笔记总结

    Java基础学习笔记一 Java介绍 Java基础学习笔记二 Java基础语法之变量.数据类型 Java基础学习笔记三 Java基础语法之流程控制语句.循环 Java基础学习笔记四 Java基础语法之 ...

  5. Mysql数据库基础学习笔记

    Mysql数据库基础学习笔记 1.mysql查看当前登录的账户名以及数据库 一.单表查询 1.创建数据库yuzly,创建表fruits 创建表 ) ) ,) NOT NULL,PRIMARY KEY( ...

  6. 0003.5-20180422-自动化第四章-python基础学习笔记--脚本

    0003.5-20180422-自动化第四章-python基础学习笔记--脚本 1-shopping """ v = [ {"name": " ...

  7. Java基础学习笔记(一)

    Java基础学习笔记(一) Hello World 基础代码学习 代码编写基础结构 class :类,一个类即一个java代码,形成一个class文件,写于每个代码的前端(注意无大写字母) XxxYy ...

  8. C#RabbitMQ基础学习笔记

    RabbitMQ基础学习笔记(C#代码示例) 一.定义: MQ是MessageQueue,消息队列的简称(是流行的开源消息队列系统,利用erlang语言开发).MQ是一种应用程序对应用程序的通信方法. ...

  9. handlebars.js基础学习笔记

    最近在帮学校做个课程网站,就有人推荐用jquery+ajax+handlebars做网站前端,刚接触发现挺高大上的,于是就把一些基础学习笔记记录下来啦. 1.引用文件: jquery.js文件下载:h ...

  10. 基础学习笔记之opencv(6):实现将图片生成视频

    基础学习笔记之opencv(6):实现将图片生成视频 在做实验的过程中.难免会读视频中的图片用来处理,相反将处理好的图片又整理输出为一个视频文件也是非经常常使用的. 以下就来讲讲基于opencv的C+ ...

随机推荐

  1. 理解 Oracle 多租户体系中(12c,18c,19c)创建角色作用域范围

    本篇探讨以下几个问题:你可提前猜测下面6个场景语句中,哪几个可以成功创建角色? 1. 在CDB级别中创建公共角色,不带 container 子句的效果: 2. 在CDB级别中创建公共角色,带 cont ...

  2. 【Unity|C#】基础篇(9)——匿名函数 / Lambda表达式

    [学习资料] <C#图解教程>(第13章):https://www.cnblogs.com/moonache/p/7687551.html 电子书下载:https://pan.baidu. ...

  3. npm 配置国内源

    淘宝镜像 npm config set registry http://registry.npm.taobao.org

  4. 初步自学Java小结

    本周学习Java使我印象最深刻的Java开发环境的安装与设置,通过下载Eclipse IDE for Java Developers初步搭建好了Java开发环境,之后利用视频了解了Java程序的类型及 ...

  5. 题解【AcWing275】[NOIP2008]传纸条

    题面 首先有一个比较明显的状态设计:设 \(dp_{x1,y1,x2,y2}\) 表示第一条路线走到 \((x1,y1)\) ,第二条路线走到 \((x2,y2)\) 的路径上的数的和的最大值. 这个 ...

  6. 【音乐欣赏】《I Do What I Want》 - Missio

    曲名:I Do What I Want 作者:Missio [00:15.84]I wish I could party like I used to when I was young [00:21. ...

  7. [P4549] 【模板】裴蜀定理 - GCD

    __gcd真好用 #include <bits/stdc++.h> using namespace std; int main() { int n,x,a=0; cin>>n; ...

  8. CentOS7.5下基于FTP服务的局域网yum源搭建

    实验环境 yum源服务器和yum客户端都处于同一局域网之中 yum源服务器 hostname:zabbix OS版本:CentOS 7.5 IP:192.168.101.201 yum客户端 host ...

  9. Request功能

    1.获取请求消息数据 获取请求行数据 获取请求头数据 获取请求体数据 请求空行没必要获取 1.获取请求行数据 GET /虚拟目录 /servlet路径  ?请求参数 HTTP/1.1 GET/day1 ...

  10. Android开发模拟器(虚拟机)的连接等操作

    前10天一直在解决android开发环境的问题,我将Androidstudio下载并安装好之后,进入IDE之后,下载AVDmanger中的虚拟机以及SDK等等.之后发现并不能运行虚拟机,根本无法打开虚 ...