How can the use of mysql_* functions in PHP be replaced with more secure and modern alternatives?
The use of mysql_* functions in PHP should be replaced with more secure and modern alternatives like mysqli or PDO to prevent SQL injection attacks and improve overall code quality. These alternatives provide better support for prepared statements, parameter binding, and error handling.
// Using mysqli as a replacement for mysql_* functions
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Example query using prepared statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "example_user";
$stmt->execute();
$result = $stmt->get_result();
// Fetch results
while ($row = $result->fetch_assoc()) {
// Process results
}
// Close statement and connection
$stmt->close();
$mysqli->close();
Related Questions
- What steps can be taken to troubleshoot and debug PHP functions that are not updating database values as expected?
- How can developers prevent email header injections and other vulnerabilities when processing form data in PHP?
- How can PHP scripts be optimized to reduce loading times and prevent delays in page rendering?