How can PHP be utilized to check if a record already exists in a database before inserting new data?
To check if a record already exists in a database before inserting new data, you can use a SELECT query to search for the record based on certain criteria (e.g., an email address or a unique ID). If the query returns a result, it means the record already exists. You can then decide whether to update the existing record or skip the insertion of new data.
// Assume $conn is the database connection object
// Check if a record with a specific email address already exists
$email = 'example@example.com';
$query = "SELECT * FROM users WHERE email = '$email'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// Record already exists, handle accordingly
echo 'Record already exists';
} else {
// Insert new data into the database
$insertQuery = "INSERT INTO users (email) VALUES ('$email')";
$conn->query($insertQuery);
echo 'New record inserted';
}