How can PHP be used to check for existing entries in a MySQL database before inserting new data?

To check for existing entries in a MySQL database before inserting new data using PHP, you can execute a SELECT query to search for a matching entry based on certain criteria (e.g., unique ID or email address). If a matching entry is found, you can choose to update the existing record instead of inserting a new one. This helps prevent duplicate entries in the database.

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check if entry already exists
$query = "SELECT * FROM table_name WHERE unique_id = '123'";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    // Entry already exists, update the record
    $updateQuery = "UPDATE table_name SET column_name = 'new_value' WHERE unique_id = '123'";
    mysqli_query($connection, $updateQuery);
} else {
    // Entry does not exist, insert new data
    $insertQuery = "INSERT INTO table_name (unique_id, column_name) VALUES ('123', 'new_value')";
    mysqli_query($connection, $insertQuery);
}

// Close database connection
mysqli_close($connection);