How can one avoid SQL syntax errors when using mysql_query in PHP?

To avoid SQL syntax errors when using mysql_query in PHP, it is important to properly escape any user input that is being included in the SQL query. This can be done using functions like mysqli_real_escape_string or prepared statements. Additionally, double-checking the SQL query syntax for any errors before executing it can help prevent issues.

// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Escape user input to prevent SQL injection
$user_input = mysqli_real_escape_string($connection, $_POST['user_input']);

// Construct the SQL query
$sql = "SELECT * FROM table WHERE column = '$user_input'";

// Execute the query
$result = mysqli_query($connection, $sql);

// Check for errors
if (!$result) {
    die("Error executing query: " . mysqli_error($connection));
}

// Process the results
while ($row = mysqli_fetch_assoc($result)) {
    // Do something with the data
}

// Close the connection
mysqli_close($connection);