我有一个PHP脚本,我正在做两个步骤,
1)从数据库中删除所有表格 2)在该空数据库中恢复默认数据库
当我通过放置URL手动运行脚本时,此代码正常工作,但每当我使用cron job运行此脚本时,第1步工作正常但数据库未恢复。
这是我的cron job命令,
[php_path] -q /home/[username]/[php_file_path]
这是我的PHP脚本,
// Name of the file
$filename = 'sample.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'my_username';
// MySQL password
$mysql_password = 'my_password';
// Database name
$mysql_database = 'my_db_name';
/*---------- Drop All tables From Database ----------*/
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
$mysqli->query('SET foreign_key_checks = 0');
if ($result = $mysqli->query("SHOW TABLES"))
{
while($row = $result->fetch_array(MYSQLI_NUM))
{
$mysqli->query('DROP TABLE IF EXISTS '.$row[0]);
}
}
$mysqli->query('SET foreign_key_checks = 1');
$mysqli->close();
/*---------- Restore Database From SQL File ----------*/
$con=mysqli_connect($mysql_host, $mysql_username, $mysql_password, $mysql_database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// ...some PHP code for database "my_db"...
// Change database to "test"
mysqli_select_db($con, $mysql_database);
// ...some PHP code for database "test"...
// Temporary variable, used to store current query
$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
mysqli_query($con, $templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}