What common error message might occur when trying to insert data into a database table in PHP?
One common error message that might occur when trying to insert data into a database table in PHP is a "SQL syntax error." This error typically happens when there is a mistake in the SQL query being executed, such as missing quotes around string values or using reserved keywords. To solve this issue, you should carefully review your SQL query to ensure it is formatted correctly.
<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Prepare and execute the SQL query to insert data into a table
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($connection->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
}
// Close the database connection
$connection->close();
?>