What are the best practices for handling insert and update operations in PHP when using mysqli?

When handling insert and update operations in PHP using mysqli, it is important to use prepared statements to prevent SQL injection attacks and improve performance. Prepared statements separate SQL logic from data input, allowing for safe execution of queries. This also helps in reusing the query multiple times with different parameters without the need to rebuild the entire query each time.

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

// Prepare an insert statement
$stmt = $mysqli->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");

// Bind parameters to the statement
$stmt->bind_param("ss", $value1, $value2);

// Set parameter values
$value1 = "value1";
$value2 = "value2";

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

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