In PHP, what methods can be employed to handle the response from an INSERT INTO statement that violates a unique constraint in MySQL?
When an INSERT INTO statement violates a unique constraint in MySQL, an error will be thrown. To handle this error in PHP, you can use a try-catch block to catch the exception and handle it accordingly. You can also use the mysqli_errno() and mysqli_error() functions to retrieve the error code and message from the MySQL server.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Attempt to insert data
try {
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $conn->error;
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
$conn->close();
?>