How can prepared statements and mysqli be used to improve the efficiency and security of PHP code when dealing with SQL queries?

When dealing with SQL queries in PHP, using prepared statements with mysqli can improve efficiency and security by separating the SQL query from the data being passed into it. This helps prevent SQL injection attacks and allows the database to optimize query execution. To implement this, you can use mysqli prepared statements to bind parameters to placeholders in the SQL query.

// Connect to database
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

// Prepare a SQL query with placeholders
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters to placeholders
$stmt->bind_param('s', $username);

// Set parameter values
$username = 'john_doe';

// Execute the query
$stmt->execute();

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

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

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