PHP中的SQL查询
在PHP中,可以使用PDO或mysqli扩展来执行SQL查询。以下是使用PDO执行查询的示例代码:
<?php
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
$sql = "SELECT * FROM your_table WHERE some_column = ?";
$stmt = $pdo->prepare($sql);
$some_value = 'some_value';
$stmt->execute([$some_value]);
$results = $stmt->fetchAll();
foreach ($results as $row) {
// 处理结果
print_r($row);
}
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
确保替换数据源名称(DSN)、数据库用户、密码和查询以适应您的数据库和需求。使用参数绑定(?
)可以防止SQL注入攻击。
评论已关闭