How can PHP be used to check if an entry already exists in a MySQL database before inserting new data?

To check if an entry already exists in a MySQL database before inserting new data, you can use a SELECT query to search for the entry based on certain criteria (e.g., a unique identifier). If the query returns a result, it means the entry already exists, and you can handle it accordingly in your PHP code.

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

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Check if entry already exists
$check_query = "SELECT * FROM table_name WHERE unique_column = 'value'";
$result = mysqli_query($connection, $check_query);

if (mysqli_num_rows($result) > 0) {
    echo "Entry already exists!";
} else {
    // Insert new data
    $insert_query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
    if (mysqli_query($connection, $insert_query)) {
        echo "New data inserted successfully";
    } else {
        echo "Error inserting data: " . mysqli_error($connection);
    }
}

// Close connection
mysqli_close($connection);