<?php 
$hostname = $config['DB_HOST'];
$user = $config['DB_USER'];
$pwd = $config['DB_PASS'];
$dbname = $config['DB_NAME'];

$files = preg_replace( "/(#.+[\r|\n]*)/" , '' , file_get_contents( ROOT . 'install/douya.sql' ) );
$sqls = split_sql_file( $files );

if(!$connect=mysql_connect($hostname,$user,$pwd) )
{
	echo "数据库联接失败";
	exit;
}
else
{

$sql = "CREATE DATABASE IF NOT EXISTS `$dbname`";
mysql_query(trim($sql),$connect);

if(!$select=mysql_select_db($dbname,$connect))
{
	echo "无法选择数据库,或数据库不存在";
	exit;
}


}

foreach( $sqls as $sql )
{
	mysql_query(trim($sql),$connect);
}

if( mysql_errno() == 0 )
{
	//echo '安装成功！';
	//rename( './install.php' , './installed-'.md5(rand(1,100).time()).'.php' );

}
else
{
	echo mysql_error();
}


 
 function split_sql_file($sql, $delimiter = ';') 
 {
        $sql               = trim($sql);
        $char              = '';
        $last_char         = '';
        $ret               = array();
        $string_start      = '';
        $in_string         = FALSE;
        $escaped_backslash = FALSE;

        for ($i = 0; $i < strlen($sql); ++$i) {
            $char = $sql[$i];

            // if delimiter found, add the parsed part to the returned array
            if ($char == $delimiter && !$in_string) {
                $ret[]     = substr($sql, 0, $i);
                $sql       = substr($sql, $i + 1);
                $i         = 0;
                $last_char = '';
            }

            if ($in_string) {
                // We are in a string, first check for escaped backslashes
                if ($char == '\\') {
                    if ($last_char != '\\') {
                        $escaped_backslash = FALSE;
                    } else {
                        $escaped_backslash = !$escaped_backslash;
                    }
                }
                // then check for not escaped end of strings except for
                // backquotes than cannot be escaped
                if (($char == $string_start)
                    && ($char == '`' || !(($last_char == '\\') && !$escaped_backslash))) {
                    $in_string    = FALSE;
                    $string_start = '';
                }
            } else {
                // we are not in a string, check for start of strings
                if (($char == '"') || ($char == '\'') || ($char == '`')) {
                    $in_string    = TRUE;
                    $string_start = $char;
                }
            }
            $last_char = $char;
        } // end for

        // add any rest to the returned array
        if (!empty($sql)) {
            $ret[] = $sql;
        }
        return $ret;
 }
?>