大家好,下面是读取.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);发布于 2013-03-09 19:03:14
这样做是不安全的,因为SQL语句中也可能有\r或\n (例如,有很多行的长文本)。
如果您确定没有这样的情况,我建议您使用trim()而不是str_replace()。它将删除每行末尾的所有空格和EOL。
<?php
$tmp = trim($line);
?>您还可以指定仅删除EOL ( "\r\n“和"\n"),如下所示:
<?php
$tmp = trim($line, "\r\n");
?>发布于 2013-03-25 11:57:14
尝试使用现有的SQL解析器库。
例如:
https://stackoverflow.com/questions/15309504
复制相似问题