標籤:
/**
* 匯出sql檔案
*/
public function exportSql(){
//需要匯出的資料庫表存入到數組當中
$tables =array("T_CRM_QUEUE_FAIL","T_CRM_QUEUE");
//定義一個變數存放sql語句
$content = ‘‘;
//開啟並寫入sql檔案
$fp = fopen("./Upload/exportSql/".date(‘Ymd‘).".sql",‘w+‘);
foreach ($tables as $k=>$v){
$content .= "\r\n-- ".$v."-- \r\n";
$sql = "SELECT * FROM ".$v;
$tablesInfo= M()->query($sql);
//將每個表的資料匯出到檔案
foreach($tablesInfo as $key=> $val){
if($val[‘CDATE‘] != $val[‘UDATE‘]){//如果添加時間和修改時間不一致,則為修改
$sqlInsert = $this->array_to_sql($val,‘update‘);
$content.="UPDATE `$v` ".$sqlInsert.";\r\n";
}else{
$sqlInsert = $this->array_to_sql($val);
$content.="INSERT INTO `$v` VALUES ".$sqlInsert.";\r\n";
}
}
}
fputs($fp,$content );//寫入檔案
fclose($fp);//關閉
}
/**
* [array_to_sql 根據數組key和value拼接成需要的sql]
* @param [type] $array [key, value結構數組]
* @param string $type [sql類型insert,update]
* @param array $exclude [排除的欄位]
* @return [string] [返回拼接好的sql]
*/
public function array_to_sql($array, $type=‘insert‘, $exclude = array()){
$sql = ‘‘;
if(count($array) > 0){
foreach ($exclude as $exkey) {
unset($array[$exkey]);//剔除不要的key
}
if(‘insert‘ == $type){
$keys = array_keys($array);
$values = array_values($array);
$col = implode("`, `", $keys);
$val = implode("‘, ‘", $values);
$sql = "(`$col`) values(‘$val‘)";
}else if(‘update‘ == $type){
$tempsql = ‘‘;
$temparr = array();
foreach ($array as $key => $value) {
$tempsql = "‘$key‘ = ‘$value‘";
$temparr[] = $tempsql;
}
$sql = implode(",", $temparr);
}
}
return $sql;
}
PHP匯出資料庫sql檔案,add和update