How can PHP be used to prevent the creation of duplicate values in a MySQL table?

To prevent the creation of duplicate values in a MySQL table using PHP, you can use a combination of PHP code and MySQL queries. One common approach is to check if the value already exists in the table before inserting a new record. This can be done by querying the database to see if a record with the same value already exists. If it does, then you can choose to either update the existing record or display an error message to the user.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Check if value already exists in the table
$value = $_POST['value'];
$sql = "SELECT * FROM table_name WHERE column_name = '$value'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Value already exists, display error message
    echo "Value already exists in the table.";
} else {
    // Value does not exist, insert new record
    $sql = "INSERT INTO table_name (column_name) VALUES ('$value')";
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

$conn->close();
?>