我导出数据库并将文件保存在文件夹中现在我想使用codeigniter在mysql数据库中导入相同的文件,以下是我的导出方法,它正常工作但现在我要导入相同的文件。
function getFeeRelatedTableBackups()
{
$this->load->dbutil();
$this->load->helper('url');
$this->load->helper('file');
$this->load->helper('download');
$this->load->library('zip');
$prefs = array(
'tables' => array('table1', 'table2', 'table3'), // Array of tables to backup.
'ignore' => array(), // List of tables to omit from the backup
'format' => 'sql', // gzip, zip, txt
'filename' => 'mybackup.sql', // File name - NEEDED ONLY WITH ZIP FILES
'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file
'add_insert' => TRUE, // Whether to add INSERT data to backup file
'newline' => "\n" // Newline character used in backup file
);
$backup=& $this->dbutil->backup($prefs);
$dbname='backup-on-'.date('Y-m-d-h:i:s').'.sql';
$save=UPLOAD_PATH_FEE_MANAGEMENT_TABLES.$dbname;
write_file($save,$backup);
force_download($dbname,$backup);
}
尝试了这两种方法来恢复,但两种方法都无法正常工作
function restoredb()
{
$isi_file = file_get_contents(UPLOAD_PATH_FEE_MANAGEMENT_TABLES.'backup-on-2018-02-12-07:57:37.sql');
$string_query = rtrim( $isi_file, "\n;" );
$array_query = explode(";", $query);
foreach($array_query as $query)
{
$this->db->query($query);
}
}
public function import_database()
{
$temp_line = '';
$lines = file(UPLOAD_PATH_FEE_MANAGEMENT_TABLES.'backup-on-2018-02-12-07:57:37.sql');
foreach ($lines as $line)
{
if (substr($line, 0, 2) == '--' || $line == '')
continue;
$temp_line .= $line;
if (substr(trim($line), -1, 1) == ';')
{
$this->db->query($temp_line);
$temp_line = '';
}
}
}
答案 0 :(得分:1)
尝试这样的事情:
public function import_database() {
$temp_line = '';
$lines = file('/path/to/file/my_file.sql');
foreach ($lines as $line)
{
if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 1) == '#')
continue;
$temp_line .= $line;
if (substr(trim($line), -1, 1) == ';')
{
$this->db->query($temp_line);
$temp_line = '';
}
}
}
答案 1 :(得分:0)
我不相信问题是评论或其他格式问题。
在阅读$this->dbutil->backup()
的输出时,以下内容对我来说非常适合。
与Shoukat答案的主要区别在于
simple_query()
代替query()
,因为后者的功能不是必需的这一直对我有用。
public function restoredb($file)
{
if (file_exists($file))
{
$lines = file($file);
$statement = '';
foreach ($lines as $line)
{
$statement .= $line;
if (substr(trim($line), -1) === ';')
{
$this->db->simple_query($statement);
$statement = '';
}
}
}
}