What are the key differences between the SELECT and INSERT SQL statements in PHP, and how should they be used correctly in database operations to avoid errors like duplicate entries?
When performing database operations in PHP, it is important to differentiate between the SELECT and INSERT SQL statements. SELECT is used to retrieve data from a database, while INSERT is used to add new data to a database. To avoid errors like duplicate entries, you can use the ON DUPLICATE KEY UPDATE clause in your INSERT statement to handle situations where a record with the same key already exists.
// Example code to insert data into a database table with ON DUPLICATE KEY UPDATE clause
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to insert data with ON DUPLICATE KEY UPDATE
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2') ON DUPLICATE KEY UPDATE column2 = 'value2'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();