What potential security risks are associated with using deprecated mysql_* functions in PHP?
Using deprecated mysql_* functions in PHP can pose security risks such as SQL injection attacks, as these functions do not support prepared statements or parameterized queries. To mitigate this risk, it is recommended to switch to mysqli or PDO extension, which provide better security features like prepared statements.
// 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);
// Execute the statement
$stmt->execute();
// Get results
$result = $stmt->get_result();
// Fetch data
while ($row = $result->fetch_assoc()) {
// Process data
}
// Close statement and connection
$stmt->close();
$mysqli->close();