大家好,下面是读取.sql文件并将每个查询存储在数组元素中的代码。在我的。sql文件中有各种语句,如CREATE TABLE, DROP, INSERT
$fileLines = file('alltables.sql');
$templine = '';
foreach ($fileLines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
$queries[] = $templine;
// Reset temp variable to empty
$templine = '';
}
}
// Here I further process $queries var
它在windows平台下工作得很好,但我不确定它是否会在linux服务器上工作,所以我想让你看看代码,让我知道我是否需要改变代码,比如('t'r'0 'x0B)来处理不同平台的新行和回车:
$tmp=str_replace("'r'n", "'n", $line);
$tmp=str_replace("'r", "'n", $line);
这样做是不安全的,因为在SQL语句中也可能有'r或'n(例如有许多行的长TEXT)。
如果你确定没有这样的情况,我建议你使用trim()而不是str_replace()。它将删除每行末尾的所有空格和EOL。
<?php
$tmp = trim($line);
?>
你也可以像这样指定只删除EOL("'r'n"answers"'n"):
<?php
$tmp = trim($line, "'r'n");
?>
尝试使用现有的SQL解析器库。
例如:- http://code.google.com/p/php-sql-parser/