How can the code be refactored to utilize PDO for database interactions instead of mysql_ functions?
The issue can be solved by refactoring the code to use PDO (PHP Data Objects) for database interactions instead of the deprecated mysql_ functions. PDO provides a more secure and flexible way to interact with databases in PHP.
<?php
// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// Prepare and execute a query using PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$user = $stmt->fetch();
// Use the retrieved data
echo $user['username'];
// Close the PDO connection
$pdo = null;
?>
Keywords
Related Questions
- What potential pitfalls should be considered when using preg_match() to search for values in a string in PHP?
- How can one troubleshoot a PHP script that is not displaying any results from a MySQL query?
- What are the potential pitfalls of comparing strings with special characters in PHP, especially in the context of database values?