How can comments and special characters in SQL queries be handled effectively when processing a .sql file in PHP?

When processing a .sql file in PHP, comments and special characters in SQL queries can be handled effectively by reading the file line by line, ignoring lines that start with '--' (comments) and using parameterized queries to handle special characters like single quotes. This ensures that the SQL queries are executed correctly without any issues.

$file = 'example.sql';
$handle = fopen($file, 'r');

if ($handle) {
    while (($line = fgets($handle)) !== false) {
        if (substr(ltrim($line), 0, 2) != '--') {
            $query = $pdo->prepare($line);
            $query->execute();
        }
    }

    fclose($handle);
} else {
    echo "Error opening the file.";
}