How can unique keys be utilized in MySQL to prevent duplicate entries and ensure data integrity when inserting new records through PHP?
To prevent duplicate entries and ensure data integrity when inserting new records through PHP in MySQL, unique keys can be utilized. Unique keys enforce the constraint that no two rows can have the same value in a specified column or combination of columns. This ensures that each record is unique and prevents duplicates from being inserted into the database.
// 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);
}
// Insert new record with unique key constraint
$sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3')";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close connection
$conn->close();
Keywords
Related Questions
- How can PHP be optimized to automatically update seasonal content without manual intervention each year?
- How can the loss of data during the transmission of form inputs be prevented in PHP?
- How can error reporting settings in PHP be optimized to provide more detailed and timely error messages for troubleshooting?