How can syntax errors in SQL queries, such as using reserved keywords like 'alter', be avoided when inserting data into a MySQL database using PHP?
To avoid syntax errors in SQL queries when inserting data into a MySQL database using PHP, you can use backticks (`) around column names to prevent conflicts with reserved keywords. This ensures that the SQL query is properly formatted and executed without errors.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data into MySQL database
$name = "John Doe";
$age = 30;
$sql = "INSERT INTO `users` (`name`, `age`) VALUES ('$name', $age)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Related Questions
- How can you extract and break down a date from a database in PHP?
- Are there any pre-built classes or functions available for highlighting PHP code in a webpage?
- What are the best practices for styling form elements in PHP using CSS classes, and how can this contribute to a more organized code structure?