What are the potential risks of using the outdated mysql_* functions in PHP and what are the recommended alternatives?
Using the outdated mysql_* functions in PHP poses security risks such as SQL injection vulnerabilities and lack of support for newer MySQL features. It is recommended to switch to mysqli or PDO for database operations, as they provide better security and support for prepared statements.
// Using mysqli as an alternative to mysql_* functions
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform a query using prepared statements
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "example";
$stmt->execute();
$result = $stmt->get_result();
// Fetch results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close statement and connection
$stmt->close();
$mysqli->close();