How can PHP scripts be optimized to handle both INSERT and UPDATE operations on a MySQL database?
To optimize PHP scripts to handle both INSERT and UPDATE operations on a MySQL database, you can use the ON DUPLICATE KEY UPDATE clause in your SQL query. This clause allows you to insert a new row into the table if the primary key does not exist, or update the existing row if the primary key already exists. This can help reduce the number of queries needed to handle both operations separately.
<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare SQL query with ON DUPLICATE KEY UPDATE clause
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2') ON DUPLICATE KEY UPDATE column2 = 'new_value'";
// Execute the query
$result = $mysqli->query($query);
// Check for errors
if (!$result) {
echo "Error: " . $mysqli->error;
}
// Close database connection
$mysqli->close();
?>