I've had the same problem and I solved using REPLACE INTO, a MySQL extension working this way:
- If the record which you want to insert does not exist, the MySQL
REPLACE inserts a new record.
- If the record which you want to insert
already exists, MySQL REPLACE deletes the old record first and then insert a new record.
I found this method useful when I don't need to remember the old values of the record.
For example, if you want to increase a value this method isn't a great way 'cause delete the old record and the old values as well.
Remember also you need to have both INSERT and DELETE privileges to use REPLACE.
Here's and example based on my code:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "REPLACE INTO table_name (name, age, current_date)
VALUES ('" . $name . "', $age, '" . date('Y-m-d') . "')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();