Home > Article > Backend Development > PHP creates and writes sql database files into the library
这篇文章介绍的内容是关于PHP创建写入sql数据库文件到库中,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
/导入数据表 $sqldata=file_get_contents(APP_PATH . 'install/data/mysql.sql'); $sqlFormat = $this->sql_split($sqldata, $dbpre);//$dbpre为数据表前缀如:yy_ 、tp_等 //创建写入sql数据库文件到库中 结束
/** * 执行SQL语句 */ $counts = count($sqlFormat); $n = intval($n); for ($i = 0; $i < $counts; $i++) { $sql = trim($sqlFormat[$i]); if (strstr($sql, 'CREATE TABLE')) { preg_match('/CREATE TABLE `([^ ]*)`/', $sql, $matches); mysqli_query($conn,"DROP TABLE IF EXISTS `$matches[1]"); $ret = mysqli_query($conn,$sql); if ($ret) { $message = '<li><span class="correct_span">√</span>创建数据表' . $matches[1] . ',完成!<span style="float: right;">'.date('Y-m-d H:i:s').'</span></li> '; } else { $message = '<li><span class="correct_span error_span">√</span>创建数据表' . $matches[1] . ',失败!<span style="float: right;">'.date('Y-m-d H:i:s').'</span></li>'; } } else { if(trim($sql) == '') continue; $ret = mysqli_query($conn,$sql); } }
function sql_split($sql, $tablepre) { if ($tablepre != "yy_") $sql = str_replace("yy_", $tablepre, $sql); $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql); $sql = str_replace("\r", "\n", $sql); $ret = array(); $num = 0; $queriesarray = explode(";\n", trim($sql)); unset($sql); foreach ($queriesarray as $query) { $ret[$num] = ''; $queries = explode("\n", trim($query)); $queries = array_filter($queries); foreach ($queries as $query) { $str1 = substr($query, 0, 1); if ($str1 != '#' && $str1 != '-') $ret[$num] .= $query; } $num++; } return $ret; }
相关推荐:
The above is the detailed content of PHP creates and writes sql database files into the library. For more information, please follow other related articles on the PHP Chinese website!