-
StackOverflow 文档
-
pdo 教程
-
准备并执行 SQL 语句
-
用法
// 1. Connect to the database (this example with MySQL)
$host = 'localhost';
$database = 'users';
$user = 'root';
$password = '';
$dsn = "mysql:host=$host;dbname=$database";
$pdo = new PDO($dsn, $user, $password);
// 2. Prepare your query
// 2.1 First way
$query_1 = "SELECT name, city FROM users WHERE id = ? AND country = ?";
$statement_1 = $pdo->prepare($query_1);
// 2.2 Second way
$query_2 = "SELECT name, city FROM users WHERE id = :id AND country = :country";
$statement_2 = $pdo->prepare($query_2);
// 3. Execute your query
// 3.1 With the first way
$statement_1->execute([1, 'US']);
// 3.2 With the second way
$statement_2->execute([
':id' => 1,
':country' => 'US'
]);
// 4. Fetch your data
$data_1 = $statement_1->fetchAll();
$data_2 = $statement_2->fetchAll();