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();
?>