What best practices should be followed when preparing and executing SQL statements in PHP using MySQLi?

When preparing and executing SQL statements in PHP using MySQLi, it is crucial to use prepared statements to prevent SQL injection attacks and improve performance. Prepared statements separate SQL logic from data input, reducing the risk of malicious input altering the query structure. Additionally, prepared statements can be reused with different parameters, making them more efficient for executing multiple similar queries.

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL statement with a placeholder for data input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters to the prepared statement
$stmt->bind_param("s", $username);

// Set the parameter values and execute the statement
$username = "example_username";
$stmt->execute();

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

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

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