How can PDO be integrated into PHP scripts for database queries?
To integrate PDO into PHP scripts for database queries, you need to establish a connection to the database using PDO, prepare and execute SQL statements, and handle any errors that may occur during the process. This ensures secure and efficient database interactions in PHP scripts.
<?php
// Establish a connection to the database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Prepare and execute SQL statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
$results = $stmt->fetchAll();
// Handle errors
if (!$results) {
die("Error fetching data from database");
}
// Process the results
foreach ($results as $row) {
echo $row['username'] . "<br>";
}
// Close the connection
$pdo = null;
?>
Related Questions
- In PHP, what are some best practices for structuring and handling form submissions that involve database updates for specific users?
- What other PHP functions or methods can be used to retrieve server information and values?
- What are the potential challenges of using custom background images and fonts for Captchas in PHP?