What is the common mistake in the provided PHP code for adding records to a database?
The common mistake in the provided PHP code is that the SQL query is not properly formatted to insert values into the database. The values are not being correctly concatenated into the query string, leading to a syntax error. To solve this issue, the values should be properly escaped and concatenated within the query string.
// Corrected PHP code for adding records to a database
$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);
}
// Escape user inputs for security
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
// Insert data into database
$sql = "INSERT INTO users (name, email, phone) VALUES ('$name', '$email', '$phone')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Related Questions
- What are best practices for error handling in cURL requests within PHP scripts?
- In the provided code snippet, what potential reasons could lead to the "Notice: Undefined offset" error in the specified line?
- Are there any specific requirements or steps to follow when defining a non-standard font in PDFlib with PHP?