How to Take Database Backup without using phpmyadmin? [duplicate] - php

This question already has answers here:
Using a .php file to generate a MySQL dump
(13 answers)
Closed 7 years ago.
How can I take backup of all tables of a database from ftp without using phpmyadmin and get the backup as a .sql file ??

Use shell_exe() to create the backup via PHP.
<?php
$dbuser = ''; // database user
$dbpass = ''; // database password
$dbhost = ''; // database host
$dbname = ''; // database name
$create = shell_exec("mysqldump --user=$dbuser --password=$dbpass --host=$dbhost $dbname> mysql_dumb.sql");
// header('Location: mysql_dumb.sql'); // you can optionally download it but secure access to the file before doing this
?>

This script would do whatever you need.
MySQL connections need to be improved though, but works fine.
<?php
// Report all errors
error_reporting(E_ALL);
/**
* Define database parameters here
*/
define("DB_USER", '');
define("DB_PASSWORD", '');
define("DB_NAME", '');
define("DB_HOST", '');
define("OUTPUT_DIR", '');
define("TABLES", '*');
/**
* Instantiate Backup_Database and perform backup
*/
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "<br /><br /><br />Backup result: " . $status;
/**
* The Backup_Database class
*/
class Backup_Database
{
/**
* Host where database is located
*/
var $host = '';
/**
* Username used to connect to database
*/
var $username = '';
/**
* Password used to connect to database
*/
var $passwd = '';
/**
* Database to backup
*/
var $dbName = '';
/**
* Database charset
*/
var $charset = '';
/**
* Constructor initializes database
*/
function Backup_Database($host, $username, $passwd, $dbName, $charset = 'utf8')
{
$this->host = $host;
$this->username = $username;
$this->passwd = $passwd;
$this->dbName = $dbName;
$this->charset = $charset;
$this->initializeDatabase();
}
protected function initializeDatabase()
{
$conn = mysql_connect($this->host, $this->username, $this->passwd);
mysql_select_db($this->dbName, $conn);
if (!mysql_set_charset($this->charset, $conn)) {
mysql_query('SET NAMES ' . $this->charset);
}
}
/**
* Backup the whole database or just some tables
* Use '*' for whole database or 'table1 table2 table3...'
* #param string $tables
*/
public function backupTables($tables = '*', $outputDir = '.')
{
try {
/**
* Tables to export
*/
if ($tables == '*') {
$tables = array();
$result = mysql_query('SHOW TABLES');
while ($row = mysql_fetch_row($result)) {
$tables[] = $row[0];
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
$sql .= 'USE ' . $this->dbName . ";\n\n";
/**
* Iterate tables
*/
foreach ($tables as $table) {
echo "Backing up " . $table . " table...";
$result = mysql_query('SELECT * FROM ' . $table);
$numFields = mysql_num_fields($result);
$sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
$sql .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $numFields; $i++) {
while ($row = mysql_fetch_row($result)) {
$sql .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $numFields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("[^\r]\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$sql .= '"' . $row[$j] . '"';
} else {
$sql .= '""';
}
if ($j < ($numFields - 1)) {
$sql .= ',';
}
}
$sql .= ");\n";
}
}
$sql .= "\n\n\n";
echo " OK" . "<br />";
}
}
catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return $this->saveFile($sql, $outputDir);
}
/**
* Save SQL to file
* #param string $sql
*/
protected function saveFile(&$sql, $outputDir = '.')
{
if (!$sql)
return false;
try {
$handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
fwrite($handle, $sql);
fclose($handle);
}
catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return true;
}
}

Related

Get value from memcach but it is null

I'm trying to get value from memcache.
value of $dataOld[$i] is null when I'm trying to read that in if statement outside of if block it contains right value.
This is my code.
My code is for get and send data .
any help will be much appreciated.
<?php
/**
* Created by PhpStorm.
* User: PC1
* Date: 9/18/2018
* Time: 11:57 AM
*/
include 'config.php';
include 'BefrestAuth.php';
include 'Publisher.php';
$memcahe = new Memcache();
$memcahe->connect("localhost", 11211);
$dataNew = json_decode($memcahe->get('keyNew'));
$memcahe->set('keyOld', json_encode($dataNew));
while (true) {
$dataNew = json_decode($memcahe->get('keyNew'));
$dataOld = json_decode($memcahe->get('keyOld'));
if (!$dataNew[0]->price) {
continue;
} else {
$str = "";
$taskolu = array();
for ($i = 0; $i < count($dataNew); $i++) {
if ((int)$dataNew[$i]->price > (int)$dataOld[$i]->price) {
echo "\n".$dataNew[$i]->price."/////".json_encode($dataOld[$i])."\n";
$str .= "name:" . $dataNew[$i]->name . " type:" . $dataNew[$i]->type . " price:" . $dataNew[$i]->price."\n";
array_push($taskolu, $dataNew[$i]);
}
if ((int)$dataOld->price > (int)$dataNew[$i]->price) {
$str .= "name:" . $dataNew[$i]->name . " type:" . $dataNew[$i]->type . " price:" . $dataNew[$i]->price."\n";
array_push($taskolu, $dataNew[$i]);
}
}
if (!empty($str)) {
$dbca = connection();
$dbca->set_charset("utf8");
$rate = "SELECT u.user_chid FROM users u";
$result = $dbca->prepare($rate);
$result->execute();
$res = $result->get_result();
while ($obj = $res->fetch_object()) {
$auth = (string)BefrestAuth::generatePublishAuth($obj->user_chid);
Publisher::publish(11812, $obj->user_chid, $auth, json_encode(array("messages" => $taskolu)));
echo "\n";
}
}
$memcahe->delete('keyOld');
$data=json_encode($dataNew);
$memcahe->set('keyOld', $data);
$dataOld = json_decode($memcahe->get('keyOld'));
}
}

Export MySQL database using PHP [closed]

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}

Backing up and Uploading DATABASE with php script. (Issue while uploading to database: sql syntax will not work because of foreignkey connection

I have a problem while uploading database with key-connection between the tables.
Script works well as far as there is no connection between the tables.
What MySql command do I have to include in my php class to drop all foreign keys ? So I'd be able to drop the tables and then after all tables have been created add the key-connection back onto the tables.
Here it is the class I am using:
<?php
class BackupDB
{
private $host = '';
private $username = '';
private $passwd = '';
private $dbName = '';
private $charset = '';
function __construct($host, $username, $passwd, $dbName, $charset = 'utf8')
{
$this->host = $host;
$this->username = $username;
$this->passwd = $passwd;
$this->dbName = $dbName;
$this->charset = $charset;
$this->initializeDatabase();
}
protected
function initializeDatabase()
{
$conn = mysql_connect($this->host, $this->username, $this->passwd);
mysql_select_db($this->dbName, $conn);
if (!mysql_set_charset($this->charset, $conn))
{
mysql_query('SET NAMES ' . $this->charset);
}
}
/**
* Backup the whole database or just some tables
* Use '*' for whole database or 'table1 table2 table3...'
* #param string $tables
*/
public
function backupTables($tables = '*', $outputDir = '.')
{
try
{
/**
* Tables to export
*/
if ($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while ($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
$sql.= 'USE ' . $this->dbName . ";\n\n";
/**
* Iterate tables
*/
foreach($tables as $table)
{
echo "Backing up " . $table . " table...";
$result = mysql_query('SELECT * FROM ' . $table);
$numFields = mysql_num_fields($result);
$sql.= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
$sql.= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $numFields; $i++)
{
while ($row = mysql_fetch_row($result))
{
$sql.= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $numFields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", "\\n", $row[$j]);
if (isset($row[$j]))
{
$sql.= '"' . $row[$j] . '"';
}
else
{
$sql.= '""';
}
if ($j < ($numFields - 1))
{
$sql.= ',';
}
}
$sql.= ");\n";
}
}
$sql.= "\n\n\n";
echo " OK" . "<br />";
}
}
catch(Exception $e)
{
var_dump($e->getMessage());
return false;
}
return $this->saveFile($sql, $outputDir);
}
/**
* Save SQL to file
* #param string $sql
*/
protected
function saveFile(&$sql, $outputDir = '.')
{
if (!$sql) return false;
try
{
$outputfilename = $outputDir . '/db-backup-' . $this->dbName . '-' . date("d.m.Y_H.i.s") . '.sql';
$result = mysql_query('INSERT INTO backuplog (backup) VALUES ("' . $outputfilename . '")');
$handle = fopen($outputfilename, 'w+');
fwrite($handle, $sql);
fclose($handle);
echo '<span class="message">Zapisano ' . $outputfilename . ' link do bazy. </span>';
echo '<span class="message">Właśnie pobrano kopie zapasową. Dziękujemy Serdecznie. Życzymy miłego dnia.</span>';
}
catch(Exception $e)
{
$result = mysql_query('DELETE FROM backuplog WHERE backup ="' . $outputfilename . '"');
var_dump($e->getMessage());
echo '<span class="error">Notacja.Udało się pobrać bazedanych... ale #NIE zaladowano linku do formularza, aby odzyskać dane trzeba ręcznie wpisać nazwę folderu/orazpliku.sql</span>';
echo '<span class="error">UWAGA! Wystąpił błąd podczas zapisywania danych w bazie... Zadanie nie ukończone.</span>';
return false;
}
return true;
} //end f
public
function loadDB($filename)
{
// $result=exec('mysql --user='.$this->user.' --password='.$this->pass .'<DatabaseBackUp/'.$filename);
// mysql -u user_name -p <file_to_read_from.sql
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '') continue;
// Add this line to the current segment
$templine.= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line) , -1, 1) == ';')
{
// Perform the query
if (!mysql_query($templine))
{
echo "Błąd ładownia pliku.sql";
return false;
} //echo $templine //TEST!
// Reset temp variable to empty
$templine = '';
}
}
return true;
} //end function
} //End calss
/* USE EXAMPLE
// DOWNLOAD DB FROM SERVER AS SQL FILE TO
$backupDatabase = new BackupDB(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "<br /><br /><br />Backup result: ".$status;
// RETRIVE DATA FROM SQL FILE TO DATABASE
$backupDatabase->loadDB("Path/to/mysqlfile.sql");
*/
?>
If you know how to extract foreign keys from a database, drop them one after the other, delete all tables and then put the keys back on again, please share your knowledge. Thanks again for looking into it.
Again for those who like to use this script it works fine... if! tables in database are not connected with foreign keys. Let's hope this state will soon change.
Short example of outputed .sql file:
CREATE DATABASE IF NOT EXISTS DATABASEONE;
USE DATABASEONE;
DROP TABLE IF EXISTS st_glowne_st_pages;
CREATE TABLE `st_glowne_st_pages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fk_glowne` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`fk_pages` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`kolejnosc` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`),
KEY `fk_glowne` (`fk_glowne`),
KEY `fk_pages` (`fk_pages`),
CONSTRAINT `st_glowne_st_pages_ibfk_1` FOREIGN KEY (`fk_glowne`) REFERENCES `st_glowne` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `st_glowne_st_pages_ibfk_2` FOREIGN KEY (`fk_pages`) REFERENCES `st_pages` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO st_glowne_st_pages VALUES("1","admin.php","pageadmin.php","1");
INSERT INTO st_glowne_st_pages VALUES("3","index.php","pageindex.php","1");
INSERT INTO st_glowne_st_pages VALUES("4","work.php","pagework.php","1");
INSERT INTO st_glowne_st_pages VALUES("7","register.php","pageregister.php","1");
INSERT INTO st_glowne_st_pages VALUES("8","login.php","pagelogin.php","1");
I haven't tried this myself, but apparently you can turn checking off.
SET FOREIGN_KEY_CHECKS = 0;
you'll need to read all the foreign key constraints and also store them in your backup file if you want to recreate them afterwards.
see this answer for some more clues.
you really should consider using sqldump though ...

Error " Using $this when not in object context" with class

I have a class like this:
<?php
class DataConnection {
private $hostName = "localhost";
private $username = "root";
private $password = "";
private $dbName = "test";
private $link = "";
public function __construct() {
}
private function connect() {
$this->link = mysql_connect($this->hostName, $this->username, $this->password)
or die ("Could not connect to the database");
mysql_select_db($this->dbName, $this->link) or die("Could not select database");
}
// lay kieu du lieu cua record trong table
public function getDataTypeTable($tableName) {
$this->connect();// ERROR HERE
$query = "SELECT * FROM {$tableName}";
$result = mysql_query($query);
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
//var_dump($results);
//mysql_free_result($results);
}
public function __destruct() {
mysql_close($this->link);
}
}
?>
I get an error "Fatal error: Using $this when not in object context in C:\xampp\htdocs\demo\test\DataConnection.php on line 44", it means that there is something wrong in connect function. How can I fix it? Thanks for watching!

Mysqli Class Always returns NULL for results with one var passed through

Every time I call a query with my class for select * from table where blank=blank it always comes up "NULL" on a var_dump for the results at the end of the class. I'm still stuck on this and don't know why it's doing it, but it sends no responses for sure, because I'm getting nothing back.
mysqli.class.php
<?php
class DATABASE
{
//set up variables only for this class
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $connection;
private $paramaters = array();
private $results = array();
private $numrows;
//call connection on call of class
public function __construct($db_host, $db_user, $db_pass, $db_name)
{
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name) or die('There was a problem connecting to the database! Error #: '. $this->mysqli->connect_errno);
}
//close mysqli connection on class close
public function __destruct()
{
$this->mysqli->close();
}
//query
public function select($fields, $table, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal, $sets, $setVal)
{
switch($type)
{
case "regular":
if ($where == null)
{
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = "";
} else {
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
case "update":
if ($where == null)
{
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal;
} else {
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal . " WHERE " . $where . " = ?";
}
break;
case "insert":
if ($sets == null)
{
$queryPre = "INSERT INTO " . $table;
$querySuff = " VALUES(" . setVal . ")";
} else {
$queryPre = "INSERT INTO " . $table . " (" . $sets . ")";
$querySuff = " VALUES(" . setVal . ")";
}
case "delete":
if ($where == null)
{
$queryPre = "DELETE FROM " . $table;
$querySuff = "";
} else {
$queryPre = "DELETE FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
}
//$sql = $queryPre . "" . $querySuff;
//var_dump($sql);
//exit;
$stmt = $this->mysqli->prepare($queryPre . "" . $querySuff) or die('There was a problem preparing the Query! Error#: '. $this->mysqli->errno);
if ($whereVal == null)
{
$stmt = $this->bindVars($stmt,$setVal);
} else {
$stmt = $this->bindVars($stmt,$whereVal);
}
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
{
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch())
{
$x = array();
foreach($row as $key => $val)
{
$x[$key] = $val;
}
$results[] = $x;
}
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
}
private function bindVars($stmt,$params)
{
if ($params != null)
{
$types = '';
//initial sting with types
if (is_array($params))
{
foreach($params as $param)
{
//for each element, determine type and add
if(is_int($param))
{
$types .= 'i'; //integer
} elseif (is_float($param))
{
$types .= 'd'; //double
} elseif (is_string($param))
{
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
} else {
if (is_int($params))
{
$types = 'i';
} elseif (is_float($params))
{
$types = 'd';
} elseif (is_string($params))
{
$types = 's';
} else {
$types = 'b';
}
}
$bind_names[] = $types;
if (is_array($params))
{
//go through incoming params and added em to array
for ($i=0; $i<count($params);$i++)
{
//give them an arbitrary name
$bind_name = 'bind' . $i;
//add the parameter to the variable variable
$$bind_name = $params[$i];
//now associate the variable as an element in an array
$bind_names[] = &$$bind_name;
}
} else {
$int0 = 0;
$bind_name = 'bind' . $int0;
$$bind_name = $params;
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
return $stmt; //return the bound statement
}
}
?>
example to call and check fields - process_availability.php:
<?php
//require necessary files
require('../config/dbconfig.php');
include('../classes/mysqli.class.php');
//initiate connection
$mysqli = new DATABASE($db_host,$db_user,$db_pass,$db_name);
//take type of check
$checktype = $_POST['type'];
//check the user name
if ($checktype == "username") {
//change post to variable
$username = $_POST['username'];
//check if user name is empty
if ($username == "") {
$validuser = array("empty", "false");
echo implode(',', $validuser);
exit;
}
//if user name is more characters than 30
if (strlen($username) > 30) {
$validuser = array("max", "false");
echo implode(',', $validuser);
exit;
}
//search for same user name in database
$resultsU = $mysqli->select('*','users','username',$username,'regular',null,null,null,null,null);
//var_dump($resultsU);
if (is_array($resultsU))
{
var_dump($resultsU);
foreach($resultsU as $rowU)
{
//return results
if($rowU['username'] == "" || $rowU['username'] == NULL)
{
//user name is blank
$validuser = array("yes", "true");
echo implode(',', $validuser);
exit;
}
else {
//username is not blank, so it's taken
$validuser = array("no", "false");
echo implode(',', $validuser);
exit;
}
}
}
}
And just to show what I'm actually doing with the information, here is a PART of the java (just handles username mostly, there is a ton more for email, ect not included):
fiddle
And, of coarse, the link to the page: page link
I've been fixing other things on here, and on a technicality it works. I get a response if there IS something in the database that matches the username i type, but if there is no match, for some reason it doesn't respond at all.....
Specifically...right at the bottom of the 2nd to last function in the class:
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
When you are returning no results to the client, you need to indicate to the client that this is what you have done, and the code shown above simply outputs nothing in this case. While it is easily possible to handle this empty response correctly on the client side a better solution would be to do one of the following:
If you need the data from the result, json_encode() the results before sending them back to the client. This would mean that if the were no results you would return an empty array, but it would still be valid JSON and crucially you can easily check whether the result array is empty on the client side using result.length.
If you don't actually need the result data and all you need is to determine whether there were any results, you can simply return a 1 or a 0. This kind of boolean response takes minimal bandwidth and minimal processing, and the best thing about it is all you need to do is evaluate it as a boolean on the client side - i.e. if (result) { /* do stuff */ }

Categories