How can SQL injection attacks be prevented in PHP applications, and what are the recommended alternatives to the deprecated mysql_ functions?

SQL injection attacks can be prevented in PHP applications by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. The deprecated mysql_ functions can be replaced with mysqli or PDO functions, which support prepared statements and help prevent SQL injection vulnerabilities.

// Using prepared statements with mysqli

$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");

// Bind parameters
$stmt->bind_param("ss", $username, $password);

// Set parameters and execute
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();

// Process the result
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Handle the query result
}

// Close the statement and connection
$stmt->close();
$mysqli->close();