I was trying to learn how to make a Database backup through PHP scripting. I landed upon various articles, but this one was quite simple →
<?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 "Backup data successfully\n";
mysql_close($conn);
?>
I am looking for a few amendments.
#1 The tables may vary in real-life situations. So I first want to Populate all tables and store it in a variable - I believe array will do the job and then take a full backup of MySQL.
Please guide me on how can I store all table details in an array first. Thanks.
P.S. End goal will be to try this on Wordpress DB.
Its in general a bad idea to use a PHP script to make backup from a database. At one point when the table reach a specific size, it will fail.
One thing you need to add at the top, is the command to make the script run until it is complete (or depending on the php settings, when the internal max time for these script run out).
set_time_limit(0);
For getting the tables of a database, you can use the INFORMATION_SCHEMA:
SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='[database name]'
$_POST tells you you’re looking for form data from the user.
Tells you your form data may send a field called ‘table’.
Based on the construction, it may send multiple values of table, and so $_POST[‘table’], if it is set, is an array.
Well it would throw an error because you’d be trying to redefine a predefined function. But my point is that that is what print_r does, even though you cant see it. That is ‘the code’ for print_r. (It will have more than that, obviously, because it does things like check type etc. But at its root, that’s what it does.)
You havent told fetchAll what kind of array you want back (numeric or associative), so it’s gone with its default - Both. The 0th column of your row is “table_in_swisskni_testpod”.