How can the use of UNIQUE INDEX or PRIMARY KEY in PHP prevent errors in database queries?
Using UNIQUE INDEX or PRIMARY KEY in PHP can prevent errors in database queries by ensuring that certain columns in a database table contain unique values. This helps to maintain data integrity and prevent duplicate entries, which can cause conflicts and inconsistencies in the database. By defining these constraints in the database schema, errors such as duplicate entry violations can be caught and handled gracefully in PHP code.
// Create a table with a UNIQUE INDEX on the 'email' column
$sql = "CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50) UNIQUE
)";
$conn->query($sql);
// Insert data with a duplicate email value
$sql = "INSERT INTO users (id, name, email) VALUES (1, 'John Doe', 'johndoe@example.com')";
$conn->query($sql); // This will throw an error due to the UNIQUE constraint