What best practices should be followed when handling SQL queries in PHP to prevent errors like "Undefined variable: id"?

When handling SQL queries in PHP, it is important to properly sanitize user input and ensure that variables are defined before using them in queries to prevent errors like "Undefined variable: id". One way to address this issue is by checking if the variable is set using isset() function before using it in the query.

// Check if the variable is set before using it in the query
if(isset($id)) {
    $query = "SELECT * FROM table WHERE id = $id";
    // Execute the query
} else {
    // Handle the case when $id is not set
}