How can one avoid inserting duplicate data into a table when using PHP and MySQL?

To avoid inserting duplicate data into a table when using PHP and MySQL, you can utilize the `INSERT IGNORE` or `INSERT ON DUPLICATE KEY UPDATE` MySQL queries. These queries will either ignore the insertion if a duplicate key constraint is violated or update the existing record with new values. Additionally, you can use a `UNIQUE` constraint on the table columns to prevent duplicates at the database level.

<?php
// Connect to MySQL database
$connection = new mysqli("localhost", "username", "password", "database");

// Check for connection errors
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Insert data into table with IGNORE option to avoid duplicates
$sql = "INSERT IGNORE INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($connection->query($sql) === TRUE) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $connection->error;
}

// Close database connection
$connection->close();
?>