What are the potential pitfalls of using outdated MySQL functions like mysql_query and mysql_real_escape_string in PHP code?
Using outdated MySQL functions like mysql_query and mysql_real_escape_string in PHP code can pose security risks and compatibility issues. These functions have been deprecated in newer versions of PHP and may not work properly or have vulnerabilities that can be exploited by attackers. It is recommended to switch to mysqli or PDO for database interactions and use prepared statements to prevent SQL injection attacks.
// Connect to MySQL using mysqli
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Use prepared statements to prevent SQL injection
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
// Fetch data from result set
while ($row = $result->fetch_assoc()) {
echo $row['username'] . "<br>";
}
// Close statement and connection
$stmt->close();
$mysqli->close();