PHP PDO Database Connection Guide
To connect to a database using PDO in PHP, you first need to install the PDO extension. Then, you can follow the steps below to connect to the database using PDO.
- Create a PDO object.
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
// 设置PDO错误模式为异常
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo '数据库连接失败:' . $e->getMessage();
}
- Perform database query.
try {
$stmt = $pdo->query('SELECT * FROM users');
// 获取查询结果
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['username'] . '<br>';
}
} catch (PDOException $e) {
echo '查询失败:' . $e->getMessage();
}
- Execute the query using preprocessing statements.
try {
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => 1]);
// 获取查询结果
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['username'] . '<br>';
}
} catch (PDOException $e) {
echo '查询失败:' . $e->getMessage();
}
The code above connects to a MySQL database using a PDO object and performs some simple query operations. It can be used to perform operations such as adding, deleting, modifying, and searching based on specific needs.