• PHP中使用PDO的预处理功能避免SQL注入


    不使用预处理功能

    <?php
    $id = $_GET['id'];
    $dsn = 'mysql:host=localhost;port=3306;dbname=database';
    try {
        $pdo = new PDO($dsn, $user, $pass);
        $sql = 'SELECT * FROM table where id = ' . $id;
        $stmt = $pdo->query($sql);
        $data = $stmt->fetchALL(PDO::FETCH_ASSOC);
        var_dump($data);
        $stmt->closeCursor();
    } catch (PDOException $e) {
        var_dump($e->getMessage());
    }
    

    使用匿名占位符预处理

    <?php
    $id = $_GET['id'];
    $dsn = 'mysql:host=localhost;port=3306;dbname=database';
    try {
        $pdo = new PDO($dsn, 'user', 'pass');
        $sql = 'SELECT * FROM table where id = ?';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        $data = $stmt->fetchALL(PDO::FETCH_ASSOC);
        var_dump($data);
        $stmt->closeCursor();
    } catch (PDOException $e) {
        var_dump($e->getMessage());
    }
    

    使用命名占位符预处理

    <?php
    $id = $_GET['id'];
    $dsn = 'mysql:host=localhost;port=3306;dbname=database';
    try {
        $pdo = new PDO($dsn, 'user', 'pass');
        $sql = 'SELECT * FROM table where id = :id';
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':id', $id);
        $stmt->execute();
        $data = $stmt->fetchALL(PDO::FETCH_ASSOC);
        var_dump($data);
        $stmt->closeCursor();
    } catch (PDOException $e) {
        var_dump($e->getMessage());
    }
    
    <?php
    $foo = $_GET['foo'];
    $bar = $_GET['bar'];
    $dsn = 'mysql:host=localhost;port=3306;dbname=database';
    try {
        $pdo = new PDO($dsn, 'user', 'pass');
        $sql = 'UPDATE table set column_foo = ? where column_bar = ?';
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(1, $foo);
        $stmt->bindParam(2, $bar);
        $stmt->execute();
        $data = $stmt->rowCount();
        var_dump($data);
        $stmt->closeCursor();
    } catch (PDOException $e) {
        var_dump($e->getMessage());
    }
    
  • 相关阅读:
    Python批量爬取唯美类图片
    查找Windows启动程序
    在Windows10中进行蓝屏排查
    在Windows 10中应该记住的完整的多指触摸板手势
    通过命令行工具远程注销用户
    Windows 7,8.1和10中的隐藏退出资源管理器选项
    找出正在使用的全局热键
    windows10中创建环境变量
    mysql高级(锁机制)
    mysql高级(查询截取分析)
  • 原文地址:https://www.cnblogs.com/zhuxiaoxi/p/10890131.html
Copyright © 2020-2023  润新知