How can one transition from using the deprecated mysql_* functions to PDO for more secure and efficient database operations in PHP?
The issue with using the deprecated mysql_* functions in PHP is that they are not secure and can leave your application vulnerable to SQL injection attacks. To transition to PDO for more secure and efficient database operations, you can rewrite your database queries using PDO prepared statements, which help prevent SQL injection attacks and provide better performance.
// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=database_name';
$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 prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results
foreach ($results as $row) {
echo $row['username'] . '<br>';
}