How can the use of mysqli_query() in PHP be optimized for better database interaction?

Using prepared statements with mysqli_query() can optimize database interaction in PHP by preventing SQL injection attacks and improving performance by reusing the query execution plan. Prepared statements allow you to separate SQL logic from data, making it more secure and efficient.

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

// Prepare a SQL query using a prepared statement
$query = mysqli_prepare($connection, "SELECT * FROM users WHERE username = ?");

// Bind parameters to the prepared statement
mysqli_stmt_bind_param($query, "s", $username);

// Set the parameter values
$username = "example";

// Execute the prepared statement
mysqli_stmt_execute($query);

// Get the result set
$result = mysqli_stmt_get_result($query);

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

// Close the prepared statement
mysqli_stmt_close($query);

// Close the database connection
mysqli_close($connection);