How can a composite unique key be used in MySQL to ensure that a row only appears once?
To ensure that a row only appears once in MySQL, you can use a composite unique key. This key consists of multiple columns that, when combined, must be unique for each row. By creating a composite unique key on the desired columns, MySQL will enforce this uniqueness constraint, preventing duplicate rows from being inserted.
// Create a table with a composite unique key
$sql = "CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100),
UNIQUE KEY unique_user_email (username, email)
)";
mysqli_query($conn, $sql);
Keywords
Related Questions
- How can PHP beginners effectively implement user input for deleting specific entries from an array stored in a text file?
- What are some best practices for handling encoding and special characters in PHP mail() function to ensure proper delivery of emails?
- How can the risk of injecting malicious syntax code be mitigated while using custom tags like [page title="..."] in PHP?