How can transitioning from using MySQL functions to mysqli functions in PHP improve code security and prevent SQL injections?

Using mysqli functions instead of MySQL functions in PHP can improve code security and prevent SQL injections by allowing for the use of prepared statements. Prepared statements separate SQL code from user input, making it impossible for malicious input to alter the SQL query structure. This helps prevent SQL injection attacks, as the database treats the input as data rather than executable code.

// Using mysqli prepared statements to prevent SQL injection
$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 = ?");
$stmt->bind_param("s", $username);

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

// Fetch results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process results
}

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