我一直在研究CodeIgniter附带的用户指南。我对dbutil()
方法非常感兴趣。特别是以下代码行:
// Load the DB utility class
$this->load->dbutil();
// Backup your entire database and assign it to a variable
$backup =& $this->dbutil->backup();
// Load the file helper and write the file to your server
$this->load->helper('file');
write_file('/path/to/mybackup.gz', $backup);
// Load the download helper and send the file to your desktop
$this->load->helper('download');
force_download('mybackup.gz', $backup);
应该备份当前加载的MySQL数据库。但遗憾的是,它无法正常工作,我收到以下消息:
遇到PHP错误
严重性:注意
消息:未定义属性:CI_Loader :: $ dbutil
文件名:views / view.php
行号:10
致命错误:在非对象中调用成员函数backup() 第10行的C:\ xampp \ htdocs \ CodeIgniter \ application \ views \ view.php
我在这里缺少什么?任何帮助都会非常感激。
答案 0 :(得分:22)
试试这个,如果您愿意,可以将格式zip更改为gz:)
$this->load->dbutil();
$prefs = array(
'format' => 'zip',
'filename' => 'my_db_backup.sql'
);
$backup =& $this->dbutil->backup($prefs);
$db_name = 'backup-on-'. date("Y-m-d-H-i-s") .'.zip';
$save = 'pathtobkfolder/'.$db_name;
$this->load->helper('file');
write_file($save, $backup);
$this->load->helper('download');
force_download($db_name, $backup);
答案 1 :(得分:7)
使用php执行此操作仅适用于非常小的数据库。如果你增加其他性能问题,你将很快遇到内存限制。
最有效的方法是使用mysqldump创建转储:
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="dbbackup.sql.gz"');
passthru("mysqldump --user=xx --host=xx --password=xx dbname | gzip");
当然,你必须拥有所需的权限才能做到这一点。
答案 2 :(得分:2)
var nestedcmd = "/absolute_path/program" +
" -input "+ server_dir +"/"+ filename
var cmd = "sshpass -p "+ server_pass +
" ssh "+ server_user +"@"+ server_ip +
" \""+ nestedcmd + "\""
println(cmd)
cmd !
使用codeigniter备份数据库的简便方法
答案 3 :(得分:1)
如果您有幸在服务器上启用了exec()
,shell_exec()
,system()
或passthru()
,也许你想要使用以下内容:
public function db_backup()
{
$DBUSER=$this->db->username;
$DBPASSWD=$this->db->password;
$DATABASE=$this->db->database;
$filename = $DATABASE . "-" . date("Y-m-d_H-i-s") . ".sql.gz";
$mime = "application/x-gzip";
header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
// $cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";
$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD --no-create-info --complete-insert $DATABASE | gzip --best";
passthru( $cmd );
exit(0);
}
答案 4 :(得分:1)
尝试这个...它已经过测试...如果你打算使用mysqli那么它会正常工作......你可能会把你的代码放在你的控制器或模型中但是我建议把它保存在your_model中&安培;从your_controller调用此函数......
public function db_backup()
{
$this->load->dbutil();
$backup =& $this->dbutil->backup();
$this->load->helper('file');
write_file('your_file_path/your_DB.zip', $backup);
}
答案 5 :(得分:1)
我是CodeIgniter的新手,但我成功完成了备份。试试这个,它会成功运行,并且很容易实现。在控制器中编写代码,然后从用于备份的视图页面调用该函数。搞定,去吧,你完成了。
function dbbackup()
{
$this->load->dbutil();
$backup =& $this->dbutil->backup();
$this->load->helper('file');
write_file('<?php echo base_url();?>/downloads', $backup);
$this->load->helper('download');
force_download('mybackup.gz', $backup);
}
对于完整的应用程序备份,请使用以下代码执行相同的过程:
function backup()
{
$this->load->helper('download');
$this->load->library('zip');
$time = time();
$this->zip->read_dir('D:xampp/htdocs/wms/');
$this->zip->download('my_backup.'.$time.'.zip');
}
您可以在此处使用您选择的任何路径。
答案 6 :(得分:1)
public function db_backup()
{
$this->load->helper('url');
$this->load->helper('file');
$this->load->helper('download');
$this->load->library('zip');
$this->load->dbutil();
$db_format=array('format'=>'zip','filename'=>'my_db_backup.sql');
$backup=& $this->dbutil->backup($db_format);
$dbname='backup-on-'.date('Y-m-d').'.zip';
$save='assets/db_backup/'.$dbname;
write_file($save,$backup);
force_download($dbname,$backup);
}`
答案 7 :(得分:1)
//load helpers
$this->load->helper('file');
$this->load->helper('download');
$this->load->library('zip');
//load database
$this->load->dbutil();
//create format
$db_format=array('format'=>'zip','filename'=>'backup.sql');
$backup=& $this->dbutil->backup($db_format);
// file name
$dbname='backup-on-'.date('d-m-y H:i').'.zip';
$save='assets/db_backup/'.$dbname;
// write file
write_file($save,$backup);
// and force download
force_download($dbname,$backup);
答案 8 :(得分:0)
这些行已从codeigniters文档中获取:
重要说明:为了初始化Utility类,您的数据库 驱动程序必须已经运行,因为实用程序类依赖于 它
调用此函数时,请检查您的数据库类是否已加载。或者您可以在加载dbutil类$this->load->database();
答案 9 :(得分:0)
试试这个!
$username = "root";
$password = "root";
$hostname = "localhost";
$dbname = "raas";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($dbname . "_" .date("Y-m-d_H-i-s").".sql"));
$command = "C:\AppServ\MySQL\bin\mysqldump --add-drop-table --host=$hostname --user=$username --password=$password ".$dbname;
system($command);
答案 10 :(得分:0)
问题是您正在尝试在引导期间尽早备份数据库。
当我尝试使用以下方法破解CodeIgniter来备份数据库时遇到了同样的问题:
$prefs = array(
'ignore'=> array('codes_cdt','codes_cpt','codes_icd10_dx_order','codes_icd10_pcs_order','pharma'),
'format'=>'gzip','filename','add_drop'=> TRUE,'add_insert'=>TRUE,'newline'=> "\n");
$filename = APPPATH.'\\backups\\' .'backup-' . date('d-m-Y') . ' .gz';
if(!file_exists($filename)){
get_instance()->load->dbutil();
file_put_contents( $filename, $this->dbutil->backup($prefs));
}
位于config.php
文件的底部。
将其移至模型并允许其自动加载,您将没事。
答案 11 :(得分:0)
<?
// Try this one, this works FOR both codeigniter and core PHP
public function Export_Database()
{
date_default_timezone_set('GMT');
// Load the file helper in codeigniter
$this->load->helper('file');
$con = mysqli_connect("localhost","username","password","databasename");
$tables = array();
$query = mysqli_query($con, 'SHOW TABLES');
while($row = mysqli_fetch_row($query)){
$tables[] = $row[0];
}
$result = 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";';
$result .= 'SET time_zone = "+00:00";';
foreach($tables as $table){
$query = mysqli_query($con, 'SELECT * FROM `'.$table.'`');
$num_fields = mysqli_num_fields($query);
$result .= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE `'.$table.'`'));
$result .= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while($row = mysqli_fetch_row($query)){
$result .= 'INSERT INTO `'.$table.'` VALUES(';
for($j=0; $j<$num_fields; $j++){
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if(isset($row[$j])){
$result .= '"'.$row[$j].'"' ;
}else{
$result .= '""';
}
if($j<($num_fields-1)){
$result .= ',';
}
}
$result .= ");\n";
}
}
$result .="\n\n";
}
//Create Folder
$folder = 'database/';
if (!is_dir($folder))
mkdir($folder, 0777, true);
chmod($folder, 0777);
$date = date('m-d-Y');
$filename = $folder."db_filename_".$date;
$handle = fopen($filename.'.sql','w+');
fwrite($handle,$result);
fclose($handle);
redirect('Dashboard');
} // end Export_Database function
?>
答案 12 :(得分:0)
// to intialize the path split the real path by dot .
public function init_path($string){
$array_path = explode('.', $string);
$realpath = '';
foreach ($array_path as $p)
{
$realpath .= $p;
$realpath .= '/';
}
return $realpath;
}
// backup database function
public function archive_database($host = '',$user ='',$pass ='',$name ='', $path = '' , $download_allow = false , $tables=false, $backup_name=false){
$CI = &get_instance();
$CI->load->database();
if($path != '')
{
$path = realpath($this->init_path($path));
}else{
if (!is_dir('archives/'))
mkdir('archives/', 0777);
$path = realpath($this->init_path('archives'));
}
if($host == '')
{
$host = $CI->db->hostname;
}
if($user == '')
{
$user = $CI->db->username;
}
if($pass == '')
{
$pass = $CI->db->password;
}
if($name == '')
{
$name = $CI->db->database;
}
set_time_limit(3000);
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; }
if($tables !== false)
{ $target_tables = array_intersect( $target_tables, $tables); }
$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--\r\n-- Database: `".$name."`\r\n--\r\n\r\n\r\n";
foreach($target_tables as $table){
if (empty($table)){ continue; }
$result = $mysqli->query('SELECT * FROM `'.$table.'`');
$fields_amount=$result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine=$res->fetch_row();
$content .= "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0) {
while($row = $result->fetch_row()) { //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 ) {$content .= "\nINSERT INTO ".$table." VALUES";}
$content .= "\n("; for($j=0; $j<$fields_amount; $j++){ $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); if (isset($row[$j])){$content .= '"'.$row[$j].'"' ;} else{$content .= '""';} if ($j<($fields_amount-1)){$content.= ',';} } $content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= ";";} else {$content .= ",";} $st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$fileLocation = $path .'\\'. $backup_name;
$file = fopen($fileLocation,"w");
fwrite($file,$content);
fclose($file);
if($download_allow){
ob_get_clean(); header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"".$backup_name."\"");
}
echo $content; exit;
}
答案 13 :(得分:0)
public function backup(){
$this->load->dbutil();
$config = array(
'format' => 'zip',
'filename' => 'insert-file-name.sql'
);
$backup =& $this->dbutil->backup($config);
$db_name = 'backup-on-'. date("Y-m-d-H-i-s") .'.zip';
$save = 'uploads/'.$db_name;
$this->load->helper('file');
write_file($save, $backup);
$this->load->helper('download');
force_download($db_name, $backup);
}
答案 14 :(得分:-3)
无需在路径
添加<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['studcourse'] ) ){
/* Generate the html and send to javascript callback to insert into select menu */
@ob_clean();
$studcourse=mysql_real_escape_string( $_POST['studcourse'] );
/*
Possible alternative SQL
------------------------
select s.`setyear`, yr.`YearName`
from `tblset` s
left outer join `tblyear` yr on yr.`id`=s.`setyear`
where s.`setcours`='".$studcourse."'
order by s.`setyear`;
*/
$sql="select `setyear`, `YearName`
from `tblset`, `tblyear`
where `tblyear`.`ID`=`tblset`.`setyear`
group by `setyear`
having `tblset`.`setcours`='".$studcourse."';";
$result=mysql_query( $sql, $connection );
if( $result ){
while( $row = mysql_fetch_array( $result ) ) {
echo "<option value='{$row[0]}'>{$row[1]}";
}
} else {
echo '<option>No results';
}
exit();
}
?>
<html>
<head>
<title>Example - set select menu based upon value from previous select menu</title>
<script type='text/javascript'>
function cbstudyear(r){
document.getElementById('studyear').innerHTML=r;
}
function setstudyear( event ){
var el=typeof( event.target )!='undefined' ? event.target : event.srcElement;
var value=el.options[ el.options.selectedIndex ].value;
var req=new XMLHttpRequest();
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
req.onreadystatechange=function(){
if( req.readyState==4 ) {
if( req.status==200 ) cbstudyear.call( this, req.response );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
req.open( 'POST', document.location.href, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( 'studcourse=' + value );
}
</script>
</html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<div class="form-group">
<label>Student Course</label>
<select name="studcourse" id='studcourse' class="form-control" onchange='setstudyear(event)'>
<?php
$result = mysql_query("select `setcours`,`course_desc`
from `tblset`, `tbl_coursetype`
where `tbl_coursetype`.`course_no`=`tblset`.`setcours`
group by `setcours`;", $connection );
if( $result ){
while( $row = mysql_fetch_array( $result ) ) {
echo "<option value=\"{$row[0]}\">{$row[1]}";
}
} else {
echo "<option>Database query failed";
}
?>
</select>
</div>
<div class="form-group">
<label>Student Year</label>
<select name="studyear" id='studyear' class="form-control">
</select>
</div>
<!--
Other form elements here presumably ~ including submit button etc
-->
</form>
</body>
</html>