PHP MYSQL UPDATE if Exist or INSERT if not?

You can use the ON DUPLICATE KEY UPDATE statement in your MySQL query when using PHP's mysqli or PDO libraries to accomplish this.

For example, using the mysqli library:

$sql = "INSERT INTO table (column1, column2, column3) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE column1 = VALUES(column1), column2 = VALUES(column2), column3 = VALUES(column3)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $column1_value, $column2_value, $column3_value);
$stmt->execute();

This will insert a new row if the primary key or unique key specified in the table schema does not exist, otherwise it will update the existing row with the new values.

Watch a course Learn object oriented PHP

You can also use REPLACE INTO statement which will work the same way as INSERT INTO statement, but if there is a duplicate key it will delete the old one and insert a new one.