What are the advantages of using PDO over mysqli_* functions for database operations in PHP?
Using PDO over mysqli_* functions in PHP offers several advantages, such as support for multiple database systems, prepared statements for preventing SQL injection attacks, and object-oriented approach for easier code maintenance and readability.
// Using PDO for database operations in PHP
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Use $result data as needed
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Keywords
Related Questions
- What are the advantages and disadvantages of using fragment identifiers in URLs for navigation within a PHP application?
- In what scenarios would it be recommended to use preg_match over other PHP functions for extracting content from a string?
- What are the potential security implications of using uniqid() to generate visitor IDs for cookies in PHP?