I have this script to access my mysql database and do some maintenance.
I am on windows platform.
Mysqldump is installed at C:\Program Files\MySQL\MySQL Server 5.7\bin
and PHP.exe is installed at C:\TCAFiles\xampp\php
I have a database.php with
<?php
// Database Connection Setup
// -------------------------------------------------------
$dbhost = '127.0.0.1';
$dbname = 'dbname';
$dbuser = 'username';
$dbpass = 'password';
// -------------------------------------------------------
$db_local = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
?>
I have a cleanup.php
<?php
// Set the protection period
$ProtectionPeriod = 97;
echo "================================\nDatabase Cleanup Started:\n================================\n";
include 'database.php';
// Do db backup
// -------------------------------------------------------
// if mysqldump is on the system path you do not need to specify the full path
// simply use "mysqldump --add-drop-table ..." in this case
$date = date("Y-m-d_H-i-s");
$dumpfname = 'D:\\Tinboye\\backups\\'.$dbname.'_'.$date.'.sql';
$command = "C:\\Program%20Files\\MySQL\MySQL%20Server%205.7\\bin\\mysqldump --add-drop-table --host=$dbhost --user=$dbuser --password=$dbpass exile > $dumpfname";
system($command);
echo "backup $dumpfname made\n\n";
// delete push bikes
$sql = "DELETE FROM vehicle WHERE class = 'Exile_Bike_OldBike' OR class = 'Exile_Bike_MountainBike'";
$result = mysqli_query($db_local, $sql);
// Delete players not logged in for $ProtectionPeriod days with less than 10 total_connections
$sql = "DELETE FROM player WHERE account_uid IN (SELECT uid FROM account WHERE last_connect_at < NOW() - INTERVAL $ProtectionPeriod DAY)";
$result = mysqli_query($db_local, $sql);
// Remove empty containers not used in 48 hours
$sql = "DELETE FROM container WHERE last_updated_at <= NOW() - INTERVAL 48 HOUR AND cargo_items = '[[],[]]' AND cargo_magazines = '[]' AND cargo_weapons = '[]' AND cargo_container = '[]'";
$result = mysqli_query($db_local, $sql);
?>
and a bat file to run the php script
#echo off
::=====================================================================================================================================
:: Database Housekeeping backup & clean
::=====================================================================================================================================
C:\TCAFiles\xampp\php\php.exe D:\Tinboye\servers\jnjexile\ExileCleanup\exile_cleanup.php
pause
but when i execute the script I get an error
================================
Database Cleanup Started:
The system cannot find the path specified.
backup D:\Tinboye\backups\exile_dayz_2016-04-09_23-30-31.sql made
Press any key to continue . . .
Terminate batch job (Y/N)?
when i go to the folder D:\Tinboye\backups there is the file created, but no data, which leads me to believe that the mysqldump is not found.
anyone see the problem here?
Related
This question already exists:
Copying a database and its tables to a new database doesn't work [duplicate]
Closed 2 years ago.
I need to do this in PHP only, can't use PhpMyAdmin because the process needs to be automated.
I've been using the following code to copy the database and its tables in to a new database with its new tables, with no change to table names, just change to database name.
Seems to work when the tables have 10 or so fields in them but I just added a table with 30-40 fields in it and it seems to fall down -as in, it doesn't copy the database table and it's table rows into the new database. Is there some error checking or buffering problems that I might be running into, or is it some other problem? Doesn't output a PDO exception error either.
here's the code:
$GLOBALS['MySQL_Host'] = "127.0.0.1";
$GLOBALS['MySQL_Username'] = "username";
$GLOBALS['MySQL_Password'] = "password";
$ExistingDatabase = "database_1";
$NewDatabase = "database_2";
// connect server 1
$dblink1 = mysqli_connect("{$GLOBALS['MySQL_Host']}", "{$GLOBALS['MySQL_Username']}", "
{$GLOBALS['MySQL_Password']}", "{$ExistingDatabase}");
// select database_1
mysqli_select_db($dblink1,"$ExistingDatabase");
// get tables from database_1
$tables = mysqli_fetch_all(mysqli_query($dblink1, "SHOW TABLES FROM $ExistingDatabase"));
// connect server 2
$dblink2 = mysqli_connect("{$GLOBALS['MySQL_Host']}", "{$GLOBALS['MySQL_Username']}",
"{$GLOBALS['MySQL_Password']}");
// select database 2
mysqli_select_db($dblink2, "{$NewDatabase}");
$n=0;
foreach($tables as $table){
// get structure from table on server 1
$tableinfo = mysqli_fetch_array(mysqli_query($dblink1,"SHOW CREATE TABLE $table[0]"));
// use found structure to make table on server 2
mysqli_query($dblink2," $tableinfo[1] ");
// select all content
$result = mysqli_query($dblink1,"SELECT * FROM $table[0] ");
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
mysqli_query($dblink2,"INSERT INTO $table[0] (".implode(", ",array_keys($row)).") VALUES
('".implode("', '",array_values($row))."')");
}
$n++;
}
mysqli_close($dblink1);
mysqli_close($dblink2);
I tried many (like 10) code snippets from stackoverflow and this was the only one I could get working. Is this a good approach? If not, what is? If so, how can I fix it to make sure it's more robust and actually works?
Remember I can't use PhpMyAdmin. Please don't close this post and link a PhpMyAdmin solution. Thanks.
Edit
I've tried the following commands and executions without success. Here's the top of the file, and the 4 trials I've tried are below it:
$GLOBALS['Dir'] = "C:/wamp64/www/projectsite/";
$dumpDir = $GLOBALS['Dir'].'Databases/';
$exisitingDatabase = "exisitingDatabaseName";
$newDatabase = "newDatabaseName";
if(!file_exists($dumpDir)){
mkdir($dumpDir);
}
$Dbh = new PDO("mysql:host=127.0.0.1:3307", $GLOBALS['MySQL_Username'],
$GLOBALS['MySQL_Password']);
1.
$Dbh->exec("mysqldump --tab={$Dumpdir} {$ExistingDatabase}");
2
$Dbh->exec("-h {$GLOBALS['MySQL_Host']} -u {$GLOBALS['MySQL_Username']} --password={$GLOBALS['MySQL_Password']} > {$Dir_and_Filename}.sql");
3
$cmd = "mysqldump -h {$GLOBALS['MySQL_Host']} -u {$GLOBALS['MySQL_Username']} --password={$GLOBALS['MySQL_Password']} {$existingDatabase} > {$newDatabase}.sql";
exec($cmd);
4
exec("mysqldump -u {$GLOBALS['MySQL_Username']} -p {$ExistingDatabase} > {$NewDatabase}.sql");
Edit
Managed to get this dumping an sql file so far:
$return_var = NULL;
$output = NULL;
$command = "$Dumpdir/mysqldump -u {$GLOBALS['MySQL_Username']} -h {$GLOBALS['MySQL_Host']} -p{$GLOBALS['MySQL_Password']} {$ExistingDatabase} > $Dumpdir/{$NewDatabase}.sql";
if(exec($command, $output, $return_var)){
echo "asd";
}else{
echo "qwe";
}
Got it.
Here's some code that works, and it's simple too..
$Dumpdir = $GLOBALS['SiteDir'].'SQL/Dbs/';
if(!file_exists($Dumpdir)){mkdir($Dumpdir);}
$return_var = NULL;
$output = NULL;
$command = "$Dumpdir/mysqldump -u {$GLOBALS['MySQL_Username']} -h {$GLOBALS['MySQL_Host']} -p{$GLOBALS['MySQL_Password']} {$ExistingDatabase} > $Dumpdir{$NewDatabase}.sql";
if(exec($command, $output, $return_var)){
echo "uio";
}else{
echo "bnm";
}
$Dbh = new PDO("mysql:host=127.0.0.1:3307", $GLOBALS['MySQL_Username'], $GLOBALS['MySQL_Password']);
$Dbh->exec("CREATE DATABASE $NewDatabase");
$sql = file_get_contents($Dumpdir.$ExistingDatabase.".sql");
$mysqli = new mysqli($GLOBALS['MySQL_Host'], $GLOBALS['MySQL_Username'], $GLOBALS['MySQL_Password'], $NewDatabase);
/* execute multi query */
if($mysqli->multi_query($sql)){
echo "cvb";
}else{
echo "zxc";
}
I am still a programming newbie, please keep that in mind.
I installed SphinxSearch on Linux Mint. I followed instructions from a Digital Ocean tutorial. I created a configuration file (sphinx.conf) as follows:
source mySource{
type = mysql
sql_host = localhost
sql_user = root
sql_pass = mypass
sql_db = test
sql_query = SELECT id, uname FROM users
sql_attr_uint = id
sql_attr_string = uname
sql_port = 3306
}
index test{
source = mySource
path = /var/lib/sphinxsearch/data
docinfo = extern
}
searchd{
listen = 9306:mysql41
log = /var/log/sphinxsearch/searchd.log
query_log = /var/log/sphinxsearch/query.log
read_timeout = 5
pid_file = /var/run/sphinxsearch/searchd.pid
seamless_rotate = 1
preopen_indexes = 1
unlink_old = 1
binlog_path = /var/lib/sphinxsearch/data
}
My PHP File
<?php
$conn = new mysqli('localhost','root','mypass','test',9306);
if($conn->connect_error){
die("Could not connect");
}else{
echo "You are connected!";
}
$query = $conn->query("SELECT * FROM test WHERE MATCH('hsmith')");
echo $query->error;
?>
PHP is throwing an error stating I am using a "Non-Object"
Any solution? Am I doing somethin entirely wrong?
Most likely the problem is in
$conn = new mysqli('localhost','root','mypass','test',9306);
As per http://php.net/manual/en/mysqli.construct.php when you pass 'localhost' in the 1st param mysqli tries to use unix socket, not a TCP socket and the port number therefore gets just ignored, i.e. you probably connect to your mysql instance instead of sphinx which then causes the problem you get.
Try:
$conn = new mysqli('127.0.0.1','','','test',9306);
instead.
Please also be aware that
echo $query->error;
is wrong since mysqli_result (http://php.net/manual/ru/class.mysqli-result.php) returned by query() does not have property 'error', you probably meant
echo $conn->error;
I have a table with some fields.status and starting_timestamps are two of them.
the default value of status is T. I want to change this to F after the 10 days.
starting_timestamps stores the time of starting.How can i do this? Iam in php-mysql platform
Create a php file e.g. cron.php with the following code.
In the following code, variables $host, $mysql_user, $mysql_password, $db, $table are to be replaced with actual database related values.
<?php
$host = 'localhost';
$mysql_user = 'root';
$mysql_password = 'your password';
$db = 'databaename';
$table='actual table name';
$link = mysql_connect($host, $mysql_user, $mysql_password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db($db, $link);
if (!$db_selected) {
die ('Can\'t use '.$db.': ' . mysql_error());
}
$result = mysql_query('UPDATE `'.$table.'`
SET status=\'F\'
WHERE
(UNIX_TIMESTAMP( now( ) ) - `starting_timestamps`) /86400 = 10');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
//close connection
mysql_close($link);
?>
Now using your hosting cpanel, go to cronjobs settings.
Here create a new cronjob which should run everyday. For cron job, enter following command.
/usr/bin/php -f 'path_to_php_script.php'
You can check attached image for how to create cron job.
Here make sure that 'path_to_php_script.php' is real physical path to cron.php file on hosting server.
Well Simple.
Create a php file and then from php file run the above query and start a cron job that will run this file everyday at certain time automatically and thus you will get your desire result.
I am using a php script to backup my database. Below is the given script:
$datestamp = date("Y-m-d_h-i-s"); // Current date to append to filename of backup file in format of YYYY-MM-DD
/* CONFIGURE THE FOLLOWING FOUR VARIABLES TO MATCH YOUR SETUP */
$dbuser = "xyz"; // Database username
$dbpwd = "*****"; // Database password
$dbname = "mydatabase"; // Database name. Use --all-databases if you have more than one
$filename = "backup-$datestamp.sql.gz"; // The name (and optionally path) of the dump file
$command = "mysqldump -u $dbuser --password=$dbpwd $dbname | gzip > $filename";
$result = system($command);
Below is the command line
php5 /var/www/vhosts/cc.astra1641.startdedicated.de/httpdocs/cron/backup.php
I have output the $result variable using var_dump to check it returns empty string. also I have tried using other methods like exec($command) or passthru($command), it doesn't work.
Here is my code
<?php
$dbuser = "root";
$dbpass = "";
$dbname = "test";
$backupfile = $dbname .time()."-".date("Y-M-D h:i:s");
//$query= "C:\\wamp\\bin\\mysql\\mysql5.5.16\\bin\\mysqldump.exe " ."-u ". $dbuser ." -p ". $dbname.">". $backupfile.".sql";
$query= "C:\wamp\bin\mysql\mysql5.5.16\bin\mysqldump.exe " ."-u ". $dbuser ." -p ". $dbname.">". $backupfile.".sql";
echo $query;
system($query);
?>
But i am always getting blank file. I am using wamp server in windows 7. I have tried with double slashes and single slashes but same result. Please help me with this essue.
N.B- One things i have not mentioned yet that, when i open this in browser, the empty backup file created, but page loading not stop,its show loading....
$query= "C:\\wamp\\bin\\mysql\\mysql5.5.16\\bin\\mysqldump.exe --user root test > upload/". time()."_backup.sql";
Finally it works. I have use --user instead of -u, as i don't have any password for wamp server, i removed --password field. Now its working fine.
The command is asking for password, you must remove --password parameter or -p flag if you mysql root user password is blank.