0) { echo "Error: You have multiple files using the same version. " . "To resolve, move some of the files up so each one gets a unique version.\n"; foreach ($errors as $error) { echo " $error\n"; } exit; } // Run all the new files. foreach (self::$migrate_files as $file) { $file_version = self::get_version_from_file($file); if ($file_version <= self::$version) { continue; } self::connect(); // $fp = @fopen(self::$migrate_path . $file, 'r'); $sqls = file_get_contents(self::$migrate_path . $file); $sqls = self::selectsql($sqls); $str = null; $num = 1; self::query('set names utf8'); self::query('BEGIN'); foreach ((array)$sqls as $val) { if (empty($val)) continue; if (is_string($val)) { if(!self::query($val)){ $num = 0; } } } if ($num == 0) { self::query('ROLLBACK'); } elseif ($num == 1) { self::query('COMMIT'); } $version = $file_version; // Output the new version number. $f = @fopen(self::$migrate_path . MIGRATE_VERSION_FILE, 'w'); if ($f) { fputs($f, $version); fclose($f); } else { echo "Failed to output new version to " . MIGRATION_VERSION_FILE . "\n"; } } } public static function query($str) { if(mysql_query($str, self::$conn)){ return true; }else{ return false; } return false; } /* * 连接数据库方法 */ public static function connect() { $db = C('DB.default'); self::$conn = mysql_connect($db['DB_HOST'].':'.$db['DB_PORT'], $db['DB_USER'], $db['DB_PWD']) or die('Error:cannot connect to database!!!' . mysql_error()); self::$link = mysql_select_db($db['DB_NAME'], self::$conn) or die('Error:fail to select!!!' . mysql_error()); } /** * 判断是否是注释 * @param $sql 获取到的sql文件内容 */ public static function selectsql($sqls){ $statement = null; $newStatement=null; $commenter = array('#','--'); $sqls = explode(';',trim($sqls));//按sql语句分开 foreach($sqls as $sql){ if (preg_match('/^(\/\*)(.)+/i',$sql)) { $sql = preg_replace('/(\/\*){1}([.|\s|\S])*(\*\/){1}/','',$sql); } $sentence = explode('/n',$sql); foreach ($sentence as $subSentence) { $subSentence = str_replace('{pre}',C('DB.default.DB_PREFIX'),$subSentence); if('' != trim($subSentence)){ //判断是否注释 $isComment = false; foreach($commenter as $comer){ if(preg_match("/^(".$comer.")/",trim($subSentence))) { $isComment = true; break; } } //不是注释就是sql语句 if(!$isComment) $newStatement[] = $subSentence; } } $statement = $newStatement; } return $statement; } }