How can conditional statements be used in PHP to check if a value already exists in a MySQL database before inserting a new value?

To check if a value already exists in a MySQL database before inserting a new value, you can use a conditional SELECT query to check if the value is present in the database. If the SELECT query returns a result, it means the value already exists, and you can choose to update the existing record or display an error message. If the query returns no result, you can proceed with the insertion of the new value.

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

// Check if the value already exists
$value = "new_value";
$query = "SELECT id FROM table_name WHERE column_name = '$value'";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    // Value already exists, display an error message or update the existing record
    echo "Value already exists in the database.";
} else {
    // Value doesn't exist, proceed with inserting the new value
    $insert_query = "INSERT INTO table_name (column_name) VALUES ('$value')";
    mysqli_query($connection, $insert_query);
    echo "Value inserted successfully.";
}

// Close the database connection
mysqli_close($connection);