Archive

Archive for October, 2011

Parse Sql con PHP


Questa comoda classe statica può essere utilizzata per ricavare l’array di istruzioni sql all’interno di un file escludendone

i relativi commenti dal parsing.

class SqlParser {
    /**
     * @purpose : Parses SQL file
     * @params none
     * @return none
     */
    public static function parse($content) {

        $sqlList = array();

        // Processing the SQL file content
        $lines = explode("\n", $content);

        $query = "";

        // Parsing the SQL file content
        foreach ($lines as $sql_line):
            if (trim($sql_line) != "" &&
                strpos($sql_line, "--") === false &&
                strpos($sql_line, "#") !== 0){

                if(empty($sql_line)) continue;
                $query .= $sql_line;
                // Checking whether the line is a valid statement
                if (preg_match("/(.*);/", $sql_line)) {
                    $query = substr($query, 0, strlen($query) - 1);
                    //store this query
                    $sqlList[] = $query;
                    //reset the variable
                    $query = "";
                }
            }
        endforeach;

        return $sqlList;
    }

}
Advertisements
Categories: PHP
%d bloggers like this: