不使用预处理功能
<?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());
}