What are the potential pitfalls of using outdated MySQL functions like mysql_query in PHP?
Using outdated MySQL functions like mysql_query in PHP can lead to security vulnerabilities such as SQL injection attacks. It is recommended to use modern alternatives like PDO or MySQLi which provide prepared statements to prevent such attacks. By switching to these alternatives, you can ensure your code is more secure and up-to-date.
// 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 prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll();