zoukankan      html  css  js  c++  java
  • 吴裕雄--天生自然 PHP开发学习:MySQL 预处理语句

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "admin";
    $dbname = "myDB";
    
    // 创建连接
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // 检测连接
    if ($conn->connect_error) {
        die("连接失败: " . $conn->connect_error);
    }
    
    // 预处理及绑定
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $firstname, $lastname, $email);
    
    // 设置参数并执行
    $firstname = "John";
    $lastname = "Doe";
    $email = "john@example.com";
    $stmt->execute();
    
    $firstname = "Mary";
    $lastname = "Moe";
    $email = "mary@example.com";
    $stmt->execute();
    
    $firstname = "Julie";
    $lastname = "Dooley";
    $email = "julie@example.com";
    $stmt->execute();
    
    echo "新记录插入成功";
    
    $stmt->close();
    $conn->close();
    ?>

    <?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 并绑定参数
        $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
        VALUES (:firstname, :lastname, :email)");
        $stmt->bindParam(':firstname', $firstname);
        $stmt->bindParam(':lastname', $lastname);
        $stmt->bindParam(':email', $email);
     
        // 插入行
        $firstname = "John";
        $lastname = "Doe";
        $email = "john@example.com";
        $stmt->execute();
     
        // 插入其他行
        $firstname = "Mary";
        $lastname = "Moe";
        $email = "mary@example.com";
        $stmt->execute();
     
        // 插入其他行
        $firstname = "Julie";
        $lastname = "Dooley";
        $email = "julie@example.com";
        $stmt->execute();
     
        echo "新记录插入成功";
    }
    catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }
    $conn = null;
    ?>
  • 相关阅读:
    字符串常量池
    JDK1.8-java.lang.Object类源码阅读
    请给你的Mysql(InnoDB)表加上主键吧
    java线程占多大的内存,占哪里的内存?
    c# 多线程
    c# 遍历文件夹及其所有文件
    T-SQL 查询语句总结
    SQL Server使用LIKE运算符进行匹配查询
    sql server中关于批处理与脚本的简单介绍
    关于SQL Server数据表的五中约束
  • 原文地址:https://www.cnblogs.com/tszr/p/10955694.html
Copyright © 2011-2022 走看看