How can the issue of overwriting previous data in the database be resolved in PHP?
Issue: The problem of overwriting previous data in the database can be resolved by using an INSERT query with an "ON DUPLICATE KEY UPDATE" clause. This clause will update the existing row if a duplicate key is found, preventing the data from being overwritten. PHP Code Snippet:
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data into the database with ON DUPLICATE KEY UPDATE clause
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2') ON DUPLICATE KEY UPDATE column2 = 'value2'";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the database connection
$conn->close();
?>