Why is it recommended to use mysqli or PDO_MySQL with prepared statements instead of mysql_* functions in PHP?

Using mysqli or PDO_MySQL with prepared statements is recommended over mysql_* functions in PHP because mysql_* functions are deprecated and no longer maintained. Prepared statements help prevent SQL injection attacks by separating SQL code from user input. This makes the code more secure and less prone to vulnerabilities.

// Using mysqli with prepared statements
$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 = ?");

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

// Set parameters and execute
$username = "john_doe";
$stmt->execute();

// Get result
$result = $stmt->get_result();

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Process data
}

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