PHP Export Database SQL file, add and update

Source: Internet
Author: User

/**
* Export SQL file
*/
Public Function Exportsql () {
Database tables that need to be exported are stored in the array
$tables =array ("T_crm_queue_fail", "T_crm_queue");

Define a variable to hold the SQL statement
$content = ";
Open and write to the SQL file
$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);
Export data from each table to a file
foreach ($tablesInfo as $key = = $val) {
if ($val [' CDATE ']! = $val [' udate ']) {//If add time and modification time are inconsistent, modify
$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);//write file
Fclose ($FP);//Close
}
/**
* [Array_to_sql is stitched into required SQL based on array key and value]
* @param [Type] $array [key, array of value structures]
* @param string $type [SQL type insert,update]
* @param array $exclude [excluded fields]
* @return [string] [Return to stitched SQL]
*/
Public Function Array_to_sql ($array, $type = ' Insert ', $exclude = Array ()) {

$sql = ";
if (count ($array) > 0) {
foreach ($exclude as $exkey) {
Unset ($array [$exkey]);//Remove the 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 Export Database SQL file, add and update

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.