I am using following code to take backup of my mysql database.
With this code, a file is created and get saved in same folder where this script is kept. It is working perfectly.
I am trying to email this file using phpmailer. But I am stucked as no file is getting attached to receiving email. (email is delivered without attached file...)
Basic code is taken from https://write.corbpie.com/php-pdo-mysql-backup-script-with-compression-option/
Help is appreciated... and thank you in advanced...
Backup creating code part is as follows :
<?php
include_once("../../include/mysqli_constants.php");
require("../../PHPMailer/class.phpmailer.php");
$db_server = constant('HST');
$db_name = constant('DBN');
$db_user = constant('USR');
$db_pass = constant('PWD');
$site_url = constant('FILEROOT');
$from_email = constant('FROMEMAIL');
$from_name = constant('FROMNAME');
$mail_to1 = 'mypersonal#gmail.com';
$mail_to1_name = 'Dr Manish Joshi';
$mail_to2 = '';
$mail_to2_name = '';
$save_dir = './';
$file_name_prefix = 'my_website_';
$date = strtolower(date('d_F_Y_H_i_s_A'));
/* Do NOT EDIT BELOW */
$backup_config = array(
'DB_HOST' => $db_server,////Database hostname
'DB_NAME' => $db_name,//Database name to backup
'DB_USERNAME' => $db_user,//Database account username
'DB_PASSWORD' => $db_pass,//Database account password
'INCLUDE_DROP_TABLE' => false,//Include DROP TABLE IF EXISTS
'SAVE_DIR' => '',//Folder to save file in
'SAVE_AS' => $file_name_prefix,//Prepend filename
'APPEND_DATE_FORMAT' => 'Y_m_d_H_i_s',//Append date to file name
'TIMEZONE' => 'Asia/Kolkata',//Timezone for date format
'COMPRESS' => true,//Compress into gz otherwise keep as .sql
);
echo backupDB($backup_config);
Email sending part is as follows :
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->Host = constant('EMAILHOST');
$mail->AddAddress(''.$mail_to1.'', ''.$mail_to1_name.'');
$mail->IsSMTP();
$mail->SMTPAuth = constant('SMTPAuth');
$mail->SMTPSecure = 'tls';
$mail->Mailer = "smtp";
$mail->SMTPDebug = constant('SMTPDEBUG');
$mail->Username = constant('SMTPUSERNAME');
$mail->Password = constant('SMTPPASSWORD');
$mail->Port = 587;
$mail->From = constant('FROMEMAIL');
$mail->FromName = constant('FROMNAME');
$mail->WordWrap = 50;
$mail->Subject = '['.$from_name.'] Cron Backup MySQL On - ' . $date;
$mail->Body = $save_string.' File is attached via cron';
$mail->AddAttachment($save_string);
if (!$mail->AddAttachment($save_string)) {
echo 'Erreur : ' . $mail->ErrorInfo . "\n";
$mail->Body .= "\n" . 'Erreur : ' . $mail->ErrorInfo;
}
if (!$mail->Send()){
echo 'Message could not be sent. <p>';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Function to create database backup is as follows and it is working OK and creating db backup and saving file in folder.
/* FUNCTION Starts */
function backupDB(array $config): string {
$db = new PDO("mysql:host={$config['DB_HOST']};dbname={$config['DB_NAME']}; charset=utf8", $config['DB_USERNAME'], $config['DB_PASSWORD']);
$db->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
date_default_timezone_set($config['TIMEZONE']);
$do_compress = $config['COMPRESS'];
if ($do_compress) {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql.gz';
$zp = gzopen($save_string, "a9");
} else {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql';
$handle = fopen($save_string, 'a+');
}
//array of all database field types which just take numbers
$numtypes = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal', 'real');
$return = "";
$return .= "CREATE DATABASE `{$config['DB_NAME']}`;\n";
$return .= "USE `{$config['DB_NAME']}`;\n";
//get all tables
$pstm1 = $db->query('SHOW TABLES');
while ($row = $pstm1->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
//cycle through the table(s)
foreach ($tables as $table) {
$result = $db->query("SELECT * FROM $table");
$num_fields = $result->columnCount();
$num_rows = $result->rowCount();
if ($config['INCLUDE_DROP_TABLE']) {
$return .= 'DROP TABLE IF EXISTS `' . $table . '`;';
}
//table structure
$pstm2 = $db->query("SHOW CREATE TABLE $table");
$row2 = $pstm2->fetch(PDO::FETCH_NUM);
$ifnotexists = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $row2[1]);
$return .= "\n\n" . $ifnotexists . ";\n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
//insert values
if ($num_rows) {
$return = 'INSERT INTO `' . $table . '` (';
$pstm3 = $db->query("SHOW COLUMNS FROM $table");
$count = 0;
$type = array();
while ($rows = $pstm3->fetch(PDO::FETCH_NUM)) {
if (stripos($rows[1], '(')) {
$type[$table][] = stristr($rows[1], '(', true);
} else {
$type[$table][] = $rows[1];
}
$return .= "`" . $rows[0] . "`";
$count++;
if ($count < ($pstm3->rowCount())) {
$return .= ", ";
}
}
$return .= ")" . ' VALUES';
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$counter = 0;
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$return = "\n\t(";
for ($j = 0; $j < $num_fields; $j++) {
if (isset($row[$j])) {
//if number, take away "". else leave as string
if ((in_array($type[$table][$j], $numtypes)) && (!empty($row[$j]))) {
$return .= $row[$j];
} else {
$return .= $db->quote($row[$j]);
}
} else {
$return .= 'NULL';
}
if ($j < ($num_fields - 1)) {
$return .= ',';
}
}
$counter++;
if ($counter < ($result->rowCount())) {
$return .= "),";
} else {
$return .= ");";
}
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$return = "\n\n-- ------------------------------------------------ \n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$error1 = $pstm2->errorInfo();
$error2 = $pstm3->errorInfo();
$error3 = $result->errorInfo();
echo $error1[2];
echo $error2[2];
echo $error3[2];
if ($do_compress) {
gzclose($zp);
} else {
fclose($handle);
}
return "{$config['DB_NAME']} saved as $save_string";
}
?>
I have edited this code and now it is working...
Edited code kept on github...
https://github.com/vaidyamanishjoshi/db-backup-with-pdo-and-email-it
Related
When i am trying to send an excel sheet as attachment in php, it shows that cannot access the file. But if i am commenting the attachment part, the mail will send perfectly. When i am trying to download the sheet it works perfectly.
Will anyone guide me how can i fix this problem?
Thank you
$select="select * from tablename";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
$csv_output = '';
$data='';
for ($i = 0; $i < $fields; $i++) {
$csv_output .= mysql_field_name($export, $i) . "\t";
}
while ($row = mysql_fetch_row($export)) {
$line = '';
foreach ($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "NULL\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line) . "\n";
}
$data = str_replace("\r", "", $data);
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username ='xxxx#gmail.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('xxxxx#gmail.com', 'name');
$mail->addAddress('xxxxx#gmail.com', 'name');
$mail->addAttachment($csv_output . "\n" . $data);
$mail->isHTML(true);
$mail->Subject = 'Report';
$mail->Body = '<b>Please find the attachment of the Report</b>';
$mail->AltBody = 'Please find the attachement of the Report';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
addAttachment expects a path to a file, not raw attachment content. Easiest fix would be to store your attachment content to a temporary file and then give the path to that.
So instead of:
$mail->addAttachment($csv_output . "\n" . $data);
You could do something like:
$report_filename = date('Y-m-d-his-').'-report.txt';
file_put_contents($report_filename, $csv_output . "\n" . $data);
$mail->addAttachment($report_filename);
//....
$mail->send();
unlink($report_filename);
Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"
I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.
the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.
I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.
<?php
include 'db.php';
function check_emailaddress($email) {
// First, we check that there is one # symbol, and that the lengths are right
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $email))
{
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
{
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) // Check if domain is IP. If not, it should be valid domain name
{
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2)
{
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++)
{
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
{
return false;
}
}
}
return true;
}
$extraParam = "";
if (isset($_GET["ex"]) ) {
$extraParam = $_GET["ex"]."---";
}
//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail; //"From: info#visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6#gmail.com";
$email_to = "" ;//"respite#safeguards-training.net";
$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;
if ($usetemplate == 0) exit; // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info#visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
// $email_address = "lyan3000#gmail.com";
// if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
/*
echo $email_from . "<br>";
echo $email_address . "<br>";
echo $email_subject . "<br>";
echo $email_message;
echo "<hr>";
*/
if (mail($email_address, $email_subject, $email_message, $email_from))
{
//echo "Reminder email sent to: " . $no['firstname'] . "<br>";
echo "Yes. <br>";
}else{
//echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
echo "No. <br>";
}
}
$file_name = "record_for_cron_expire_email.txt";
$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');
$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);
//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;
$variable = array(
'{$learnerCourse}' => $learnercourse,
'{$date}' => $date
);
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);
//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
SET a04Status = 0
WHERE a04ExpirationDate <= '$expiredRightNow'
AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>
mysqli_result::fetch_all() requires MySQL Native Driver (mysqlnd).
chances are you might be missing it.
have a look at this posts, that might help you.
mysqli fetch_all() not a valid function?
below is the minimal code I can think of:
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
if (mail($email_address, $email_subject, $email_message, $email_from))
{
echo "Yes. <br>";
}else{
echo "No. <br>";
}
}
I am trying to save my data coming from my localhost database to our live server database using PHP. I am getting a successful response but whenever I try to check the our live database server there is no data in it or the data was not inserted or updated.
Also the response I get is this "Import successful! Found a total of 4 records in patient.file" even though the file I am importing is only to data.
Here is my code:
<?php
//============FUNCTIONS=================
function export_table($target_table,$sdate,$edate,$station){
$i = mysql_num_rows(mysql_query("DESCRIBE $target_table"));
$get_columns = mysql_query("SHOW COLUMNS FROM " . $target_table);
while($row_columns = mysql_fetch_array($get_columns)){
$column_name = $row_columns['Field'] . "|";
$csv_output .= $column_name;
}
$csv_output = rtrim($csv_output, "|");
$csv_output .= "\r\n";
$values = mysql_query("SELECT * FROM ".$target_table." WHERE
dateEncoded >= '2017-07-01' and dateEncoded <= '2017-07-07'");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
if($rowr[$j] == NULL){$rowr[$j] = "NULL";}
if($j==($i-1)){$csv_output .= str_replace(array("\n", "\r"), '', $rowr[$j]);
}else{$csv_output .= str_replace(array("\n", "\r"), '', $rowr[$j])."|";}
}// end for
$csv_output .= "\r\n";
}// end while
return $csv_output;
}// end function export_table
//========CREATION OF THE FILE===========================
include_once "../ewcfg8.php";
include_once "../dbcon.php";
date_default_timezone_set('Asia/Manila');
ini_set('memory_limit', '-1');
set_time_limit(0);
// $startdate = '2017-06-01';
// $enddate = '2017-07-07'; ;
// $defaulStation = $_POST['defaultStation'];
$tables = array('patient',
'tb_adr',
'tb_case',
'tb_casecomment',
'tb_comorbidity',
'tb_consilium',
'tb_consultations',
'tb_contact',
'tb_pe',
'tb_prescript',
'tb_prevcase',
'tb_resultculture',
'tb_resultgx',
'tb_resultdst',
'tb_resultdstdrug',
'tb_resulthiv',
'tb_resultxray',
'tb_symptom',
'tb_resultdssm',
'tb_dot');
//put tables in an array within an array(make a multi-dimensional array)
$dl_table = array();
foreach ($tables as $table) {
$content = export_table($table,$startdate,$enddate,$defaulStation);
$dl_table[$table] = $content;//multi-dimensional array
}
//#mysql_close($con); //close localhost connection
//=========INSERTING VALUES TO DATABASE===============
//===============Open New Connection And Connect to Live Database========
$dbhost = "http/mywebsite.example";
$localport = "3306";
$dbuser = "user";
$dbpass = "12345";
$dbname = "myonlinedb";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $conn);
$fieldseparator = "|";
$lineseparator = "\n";
foreach ($tables as $table) {
$databasetable = $table;
$csvfile = $dl_table[$table]; //variable that hold the multi-dimensional array
$lines = 0;
$header = 0;
$queries = "";
$linearray = array();
$columns = array();
//====================================Get the Columns (First line in the CSV)===================================
while(($header == 0 && $columns = fgetcsv(${$table},0,"|")) != false){
$header = 1;
$num_columns = count($columns);
$list_columns = "";
for ($c=0; $c < $num_columns; $c++) {
$list_columns .= "`" . $columns[$c] . "`" . ", ";
}
$list_columns = substr($list_columns,0,-2);
//echo $list_columns . "<br /><br />";
break;
}// close while(($columns = fgetcsv($file,0,"|")) !== false && $header == 0)
//====================================Get the contents of the CSV===================================
//Set the header to skip the first row
$header = 0;
//opening the csv file
// $size = filesize($csvfile);
// echo $size;
// if(!$size) {echo "File is empty.\n";}
// $csvcontent = fread($file,$size);
// fclose($file);
//foreach(split($lineseparator,$csvcontent) as $line)
foreach(explode($lineseparator,$csvfile) as $line) {
//if($header == 0){
//$header = 1;
//}else{
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
//*********get the csvID id and the columns in the db table to know if an insert or update will be performed****************
if ($databasetable == "patient"){
$csvID = $linearray[2];
$searchField = "patientID";
}else if($databasetable == "tb_case"){
$csvID = $linearray[0];
$searchField = "caseID";
}else if($databasetable == "tb_resultdstdrug"){
$csvID = $linearray[1]. $linearray[2];
$searchField = "CONCAT(caseIDplus, series)";
}else{
$csvID = $linearray[1]. $linearray[2];
$searchField = "CONCAT(caseID, series)";
}
//***********convert id of each row to 0*******************************
if($databasetable != "tb_case"){$linearray['0'] = '';}
//*****************search the csvID in the database************************************
$searchID = mysql_query("SELECT * FROM $databasetable WHERE $searchField = '$csvID'");
//******************count the number of columns in csv and the db table**************
$countcsv = count($linearray);
$countColumns = $num_columns;
//$countColumns = mysql_num_fields($searchID);
//****************count if the csvID exists in the database********************************
$countResults = mysql_num_rows($searchID);
//*************************get the date encoded in the csv and db table***************
$row = mysql_fetch_assoc($searchID);
$db_dateEncoded = $row['dateEncoded'];
if($databasetable == "tb_dot"){$csv_dateEncoded = $linearray[($countcsv-3)];}
else{$csv_dateEncoded = $linearray[($countcsv-2)];}
//*****************if else statement for checking number of fields****************************************
if ($countResults > 0){
//if a result was found, UPDATE the row
if ($csv_dateEncoded>$db_dateEncoded){
// if table is dot, delete all dot of the tb_case
$query = "UPDATE $databasetable SET ";
$i = 1;
while ($i < $countColumns){
$meta = mysql_fetch_field($searchID, $i);
if($linearray[$i] == "NULL"){
$query .= $columns[$i] . "=" . $linearray[$i];
//if last field
if($i == ($countColumns-1)){$query .= " WHERE $searchField = '$csvID';";}else{$query .= ",";}
}else{
$query .= $columns[$i] . "='" . $linearray[$i];
//if last field
if($i == ($countColumns-1)){$query .= "' WHERE $searchField = '$csvID';";}else{$query .= "',";}
}//end if($linearray[$i] == "NULL")
$i = $i + 1;
}//close while ($i < $countColumns)
}// end if($csv_dateEncoded>=$db_dateEncoded)
}else{//if no id was found, INSERT a new row
//$query = "INSERT INTO $databasetable VALUES(";
if($databasetable == 'patient'){$query = "INSERT INTO $databasetable VALUES(";}
else{$query = "INSERT INTO $databasetable ($list_columns) VALUES(";}
$i = 0;
while ($i < $countColumns){
if($linearray[$i] == "NULL"){
$query .= $linearray[$i];
if($i == ($countColumns-1)){$query .= ");";}else{$query .= ",";}
}else{
$query .= "'" . $linearray[$i];
if($i == ($countColumns-1)){$query .= "');";}else{$query .= "',";}
}
$i = $i + 1;
}//end While
}// close if ($countResults > 0){
//$queries .= $query . "\n";
//print "$query<br />";
#mysql_query($query);
//}//close if($header == 0)
}// close foreach(split($lineseparator,$csvcontent) as $line)
//unlink("data_uploading/files/" . $user . "/" . $databasetable . ".csv");
echo "Import successful! Found a total of $lines records in $table.file.\n<br /><br />";
//mysql_close($conn);
#mysql_close($con);
//====================================Get the Contents===================================
}//close foreach ($tables as $table)
//rmdir("data_uploading/files/" . $user);
//==========END OF INSERTING VALUES TO DATABASE ===========
i'm trying to loop a variable whose data populates from another loop of array's
HERE is the loop
for ($i=0; $i < $cid; $i++){
$message .= '<tr>
<td>'.$pcode.'</td>
<td>'.$pname.'</td>
<td>'.$pprice.'</td>
<td>'.$pqty.'</td>
</tr>';
}
And the variables in <td></td> are generated from this loop
foreach($_POST['item_cid'] as $key => $value) {
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
}
I don't know how to make this loop work, I got no errors on submit,
am i looping it correctly?
The Updated Code:
<?php
session_start();
require('admin/connect.php');
require('includes/phpmailer/PHPMailerAutoload.php');
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$resultArr = array();
$i = 0;
foreach($_POST['item_cid'] as $key => $value) {
//Data for Orders Table
$cid = intval(mysqli_real_escape_string($connection,$value));
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
//SOLUTION FROM SANJAY
$resultArr[$i] = array('cid' => $cid, 'pcode' => $pcode, 'pname' => $pname, 'pprice' => $pprice, 'pqty' => $pqty);
$i++;
//Data for Customers Table
$cname = mysqli_real_escape_string($connection,$_POST['item_cname'][$key]);
$cemail = mysqli_real_escape_string($connection,$_POST['item_cemail'][$key]);
$cphone = mysqli_real_escape_string($connection,$_POST['item_cphone'][$key]);
$caddress = mysqli_real_escape_string($connection,$_POST['item_caddress'][$key]);
$ctotal = mysqli_real_escape_string($connection,$_POST['item_ctotal'][$key]);
//$sql = "INSERT INTO orders (cid, ordprod_code, ordprod_name, ordprod_price, ordprod_qty) VALUES ('$value', '$pcode', '$pname', '$pprice', '$pqty')";
//$sql2 = "INSERT INTO customers (cid, cname, cemail, cphone, caddress, ctotal) VALUES ('$value','$cname','$cemail','$cphone','$caddress','$ctotal')";
if ($connection->query($sql) === TRUE) {
echo "Orders record created successfully \n";
}
// } else {
// echo "Error: " . $sql . "<br>" . $connection->error;
// }
if ($connection->query($sql2) === TRUE) {
echo "Customers record created successfully \n";
}
// } else {
// echo "Error: " . $sql2 . "<br>" . $connection->error;
} // close the loop
print_r($resultArr);
//********************************
// START EMAIL FUNCTION
//********************************
$message = '<html><body>';
$message .= '<img src="http://cdn.example.com/static/images/emailhead.jpg" alt="MY Site" />';
$message .= '<h3>Customer Information:</h3>';
$message .= '<table rules="all" border="1" style="border-color: #ccc;" cellpadding="10">';
$message .= '<tr><td><strong>CustomerID</strong></td><td>'. $cid .'</td></tr>';
$message .= '<tr><td><strong>Name:</strong></td><td>'. $cname .'</td></tr>';
$message .= '<tr><td><strong>Email:</strong></td><td>'. $cemail .'</td></tr>';
$message .= '<tr><td><strong>Phone:</strong></td><td>'. $cphone .'</td></tr>';
$message .= '<tr><td><strong>Address:</strong></td><td>'. $caddress .'</td></tr>';
$message .= '</table>';
$message .= '<br />';
$message .= '<h3>Order Details:</h3>';
$message .= '<table rules="all" border="1" style="border-color: #ccc;" cellpadding="10">';
$message .= '<tr style="background:#eee;">
<td><strong>Product Code</strong></td>
<td><strong>Product Name</strong></td>
<td><strong>Product Price</strong></td>
<td><strong>Product Qty</strong></td>
</tr>';
// SOLUTION FROM SANJAY
$i = 0;
for ($i=0; $i < ((isset($resultArr[$i]['cid']) && count($resultArr[$i]['cid']) > 0 ) ?$resultArr[$i]['cid'] : 0); $i++)
{
$message .= '<tr>
<td>'.$resultArr[$i]['pcode'].'</td>
<td>'.$resultArr[$i]['pname'].'</td>
<td>'.$resultArr[$i]['pprice'].'</td>
<td>'.$resultArr[$i]['pqty'].'</td>
</tr>';
}
$message .= '<tr style="background:#eee;">
<td colspan="2">Total Amount</td>
<td>'.$ctotal.'</td>
<td></td>
</tr>';
$message .= '</table>';
$message .= '</body></html>';
$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
if (preg_match($pattern, $cemail)) {
$cleanedFrom = $cemail;
} else {
return "The email address you entered was invalid. Please try again!";
}
//***************************************
// SEND MAIL USING GMAIL SMTP SERVER
//***************************************
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->Port = 587; //Set the SMTP port number - 587 for authenticated TLS
$mail->setFrom(''.$cemail.'', ''.$cname.''); //Set who the message is to be sent from
$mail->addReplyTo(''.$cemail.'', ''.$cname.''); //Set an alternative reply-to address
$mail->addAddress('owner#example.com', 'YAQOOB'); // Add a recipient
$mail->addAddress('owner#example.com'); // Name is optional
$mail->addCC('');
$mail->addBCC('');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->addAttachment('/user/file.doc'); // Add attachments
$mail->addAttachment('/images/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New order arrived from CustomerID #'.$cid.'';
$mail->Body = ''.$message.'';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
} // Data Inserted & Emailed Close IF Statement
session_destroy();
?>
Try this:
$message = "";
$resultArr = array();
$i = 0;
foreach($_POST['item_cid'] as $key => $value)
{
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
$resultArr[$i] = array('cid' => $cid, 'pcode' => $pcode, 'pname' => $pname, 'pprice' => $pprice, 'pqty' => $pqty);
$i++;
}
$i = 0;
for ($i=0; $i < (isset($resultArr[$i]['cid']) && $resultArr[$i]['cid'] ?$resultArr[$i]['cid'] : 0); $i++)
{
$message .= '<tr>
<td>'.$resultArr[$i]['pcode'].'</td>
<td>'.$resultArr[$i]['pname'].'</td>
<td>'.$resultArr[$i]['pprice'].'</td>
<td>'.$resultArr[$i]['pqty'].'</td>
</tr>';
}
What about something like this?
$message = "";
foreach($_POST['item_cid'] as $key => $value)
{
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
for ($i=0; $i < $cid; $i++)
{
$message .= '<tr>
<td>'.$pcode.'</td>
<td>'.$pname.'</td>
<td>'.$pprice.'</td>
<td>'.$pqty.'</td>
</tr>';
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I've build a php/mysql (wamp) application and deployed on a local workstation.
My customer wants to save db and restore it when he likes.
I've found this code for saving:
<?php
$DB_HOST = "localhost";
$DB_USER = "root";
$DB_PASS = "admin";
$DB_NAME = "dbname";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$tables = array();
$result = mysqli_query($con,"SHOW TABLES");
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($con, "SELECT * FROM ".$table);
$num_fields = mysqli_num_fields($result);
$return .= 'DROP TABLE '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE '.$table));
$return .= "\n\n".$row2[1].";\n\n";
for ($i=0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO '.$table.' VALUES(';
for ($j=0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"'.$row[$j].'"';} else { $return .= '""';}
if($j<$num_fields-1){ $return .= ','; }
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$handle = fopen('backup.sql', 'w+');
fwrite($handle, $return);
fclose($handle);
echo "success";
?>
This code saves file in a default folder.
What I need is to let user to decide where to save backup file or simply download it through browser.
On the other hand user needs to restore from the file he wants so I need a 'browse' button to let him choose the file in any of his folder.
My database is utf8_general_ci and has english, french and italian language I don't need complex codes because I wouldn't know how to manage them :-(
Thanks in advance.
Best way to export database using php script.
Or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "Your Username";
$mysqlPassword = "Your Password";
$mysqlHostName = "Your Host";
$DbName = "Your Database Name here";
$backup_name = "mybackup.sql";
$tables = "Your tables";
//or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$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);
}
foreach($target_tables as $table)
{
$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 = (!isset($content) ? '' : $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";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$backup_name = $backup_name ? $backup_name : $name.".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content; exit;
}
?>
This tool might be useful, it's a pure PHP based export utility: https://github.com/2createStudio/shuttle-export
Try the following.
Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
?>
To restore the backup you just need to run LOAD DATA INFILE query like this:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'yourtable.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
?>
In *nix systems, use the WHICH command to show the location of the mysqldump, try this :
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'test';
$mysqldump=exec('which mysqldump');
$command = "$mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname > $dbname.sql";
exec($command);
?>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not take data backup: ' . mysql_error());
}
echo "Backedup data successfully\n";
mysql_close($conn);
?>
Here is my code, This will backup MySQL database and store it in the specified path.
<?php
function backup_mysql_database($options){
$mtables = array(); $contents = "-- Database: `".$options['db_to_backup']."` --\n";
$mysqli = new mysqli($options['db_host'], $options['db_uname'], $options['db_password'], $options['db_to_backup']);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$results = $mysqli->query("SHOW TABLES");
while($row = $results->fetch_array()){
if (!in_array($row[0], $options['db_exclude_tables'])){
$mtables[] = $row[0];
}
}
foreach($mtables as $table){
$contents .= "-- Table `".$table."` --\n";
$results = $mysqli->query("SHOW CREATE TABLE ".$table);
while($row = $results->fetch_array()){
$contents .= $row[1].";\n\n";
}
$results = $mysqli->query("SELECT * FROM ".$table);
$row_count = $results->num_rows;
$fields = $results->fetch_fields();
$fields_count = count($fields);
$insert_head = "INSERT INTO `".$table."` (";
for($i=0; $i < $fields_count; $i++){
$insert_head .= "`".$fields[$i]->name."`";
if($i < $fields_count-1){
$insert_head .= ', ';
}
}
$insert_head .= ")";
$insert_head .= " VALUES\n";
if($row_count>0){
$r = 0;
while($row = $results->fetch_array()){
if(($r % 400) == 0){
$contents .= $insert_head;
}
$contents .= "(";
for($i=0; $i < $fields_count; $i++){
$row_content = str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));
switch($fields[$i]->type){
case 8: case 3:
$contents .= $row_content;
break;
default:
$contents .= "'". $row_content ."'";
}
if($i < $fields_count-1){
$contents .= ', ';
}
}
if(($r+1) == $row_count || ($r % 400) == 399){
$contents .= ");\n\n";
}else{
$contents .= "),\n";
}
$r++;
}
}
}
if (!is_dir ( $options['db_backup_path'] )) {
mkdir ( $options['db_backup_path'], 0777, true );
}
$backup_file_name = $options['db_to_backup'] . " sql-backup- " . date( "d-m-Y--h-i-s").".sql";
$fp = fopen($options['db_backup_path'] . '/' . $backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
echo "Backup file created '--$backup_file_name' ($result)";
}
fclose($fp);
return $backup_file_name;
}
$options = array(
'db_host'=> 'localhost', //mysql host
'db_uname' => 'root', //user
'db_password' => '', //pass
'db_to_backup' => 'attendance', //database name
'db_backup_path' => '/htdocs', //where to backup
'db_exclude_tables' => array() //tables to exclude
);
$backup_file_name=backup_mysql_database($options);
If you dont have phpMyAdmin, you can write in php CLI commands such as login to mysql and perform db dump. In this case you would use shell_exec function.
I would Suggest that you do the folllowing,
<?php
function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false)
{
$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--Database: `" . $name . "`\r\n\r\n\r\n";
foreach ($target_tables as $table)
{
$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";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
echo $content;
exit;
}
?>
The enitre project for export and import can be found at https://github.com/tazotodua/useful-php-scripts.
I would Suggest that you do the folllowing,
<?php
$con = mysqli_connect('HostName', 'UserName', 'Password', 'DatabaseName');
$tables = array();
$result = mysqli_query($con,"SHOW TABLES");
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($con, "SELECT * FROM ".$table);
$num_fields = mysqli_num_fields($result);
$return .= 'DROP TABLE '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE '.$table));
$return .= "\n\n".$row2[1].";\n\n";
for ($i=0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO '.$table.' VALUES(';
for ($j=0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"'.$row[$j].'"';} else { $return .= '""';}
if($j<$num_fields-1){ $return .= ','; }
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$handle = fopen('backup.sql', 'w+');
fwrite($handle, $return);
fclose($handle);
echo "success";
?>
upd. fixed error in code, added space before VALUES in line $return .= 'INSERT INTO '.$table.'VALUES(';
You can use this command it works or me 100%
exec('C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -uroot DatabaseName> c:\\database_backup.sql');
note:
C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe is the path for mysqldump app , check on your pc.
-uroot is -u{UserName}
If your database is protected with password then add after -uroot this sentense -p{YourPassword}