I have a PHP script in which I am doing two steps,
1) Deleting all tables from database
2) Restoring default database in that empty database
This code is working properly when I manually run the script by putting the URL but whenever I am running this script with cron job then 1st step is working properly but database is not getting restored.
here is my cron job command ,
[php_path] -q /home/[username]/[php_file_path]
here is my php script,
// 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 = '';
}
}
Related
I am trying to import a database using system() in php.
It works fine when my sql file is correct.
lets say i have an error in the sql file(for eg. syntax error).
I want that exact error in a variable so I can maintain a log and alert purpose.
<?php
$lastline = system("mysql -u root mydbname < /home/mydbname.sql ",$retval);
echo "\nretval:";
print_r($retval);
echo "\nlastline:";
print_r($lastline);
?>
Unfortunately I don't get any errors in return when my sql is improper
When I run the above code I get to see the errors on terminal but it does not save the errors in the variables.
<?php
$filename = '/home/mydbname.sql';
$mysql_host = 'localhost';
$mysql_username = 'root';
$mysql_password = '';
$mysql_database = 'mydbname';
// Connect to MySQL server & Select database
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// Temporary variable, used to store current query
$templine = '';
$lines = file($filename);
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
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>
Maybe importing this way would work, not sure this is what you need but it should work.
Code from How to import .sql file in mysql database using php
You could use the --force (-f) flag so that MySQL doesn't stop and just log any errors to the console:
mysql -u userName -p -f -D dbName < script.sql
<?php
$lastline = system("mysql -u root -f mydbname < /home/mydbname.sql ",$retval);
echo "\nretval:";
print_r($retval);
echo "\nlastline:";
print_r($lastline);
?>
PHP docs on exec() specify an additional 2 parameters for output and return value so maybe try getting both and one might include an error message.
Hope this helps
I have tried for importing SQL external file to the database in code igniter
please check the given code is correct or not.
If the code is not appropriate then please recommend for newly code///
<!DOCTYPE html>
<html>
<body>
<form action="upload.php">
Select a file: <input type="file" name="img">
<input type="submit">
</form>
</body>
</html>
the JavaScript is as follows
<?php
// Name of the file
$filename = 'churc.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '';
// Database name
$mysql_database = 'dump';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// 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
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>
New to php and mysql,
I am trying to insert a exported sql file into a remote DB.
I am try this code from 1and1 but it is not working.
$create_install_db_server = 'testdb.example.com';
$create_install_db_username = 'test123';
$create_install_db_password = 'test789';
$create_install_db_name = 'test';
$sqlfile = '/home/path/to/localsql.sql';
$command='mysql -h' . $create_install_db_server .' -u' . $create_install_db_username .' -p' . $create_install_db_password .' ' . $create_install_db_name .' < ' . $sqlfile;
exec($command,$output=array(),$worked);
switch($worked){
case 0:
echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
break;
case 1:
echo 'There was an error during import.';
break;
}
#srikanth, I have an another way to do this, try this one
<?php
// Name of the file
$filename = 'churc.sql';
// MySQL host
$mysql_host = 'testdb.example.com';
// MySQL username
$mysql_username = 'test123';
// MySQL password
$mysql_password = 'test789';
// Database name
$mysql_database = 'Test';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// 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
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>
Hope this helps you. :)
Note: mysql usage is deprecated, instead you can make use of Mysqli,PDO like below.
$db = new PDO($mysql_host, $mysql_username, $mysql_password);
$sql = file_get_contents('churc.sql');
$qr = $db->exec($sql);
for executing big sql files my above answer is not enough so i suggest you to take a look at #Abu sadat answer here
Try the following things
Do an echo of the command before you try to execute it
Try running the command on the terminal - check if this is successful
If it is successful, replace your exec with a simple command (like 'touch /tmp/abc.txt') and check if a file is getting created.
By doing this, you are trying to find out if there is a problem with your mysql command or there is an issue with the exec function in php
Ok, I've been pulling my hairs for few days and can't find out what's happening. I can successfully import mysql dump file through phpmyadmin but whenever I try to import it into the database using any php script it, gives me error. Currently, I'm using this script.
<?php
$mysqlDatabaseName = 'dbnname';
$mysqlUserName = 'username';
$mysqlPassword = 'password';
$mysqlHostName = 'localhost';
$mysqlImportFilename = dirname(__FILE__) . '/database.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$con = mysqli_connect($mysqlHostName, $mysqlUserName, $mysqlPassword, $mysqlDatabaseName);
if (!$con) {
die('connection failed');
}
$command = 'mysql -h' . $mysqlHostName . ' -u' . $mysqlUserName . ' -p' . $mysqlPassword . ' ' . $mysqlDatabaseName . ' < ' . $mysqlImportFilename;
$result = mysqli_query($con, $command);
if ($result) {
print_r('True $result: ' . $result);
} else {
print_r('False $result: ' . $result . mysqli_errno($con));
} // TODO need to print mysqli_errno
Error I'm getting when using script:-
False $result: 1064
There is no error while manually importing through phpmyadmin.
Thanks
The $command which you are feeding to mysqli is the call for the standalone mysql command line interface and not a mysqli function call. Use the PHP system() or similar functions to call the external mysql CLI.
Try this
<?php
// Name of the file
$filename = 'database.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '';
// Database name
$mysql_database = 'dbnname';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// 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
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>
Good Luck
I am exporting a SQL Server table to a CSV using php (see code below). What I am needing help with is including the headers of the columns in the export. I can do this when I export from MySQL, but cannot figure it out with SQL Server. If anyone can point me in the right direction I would appreciate it.
<?php
// SQL Server connection string details.
$myServer = "server";
$myUser = "user";
$myPass = "password";
$myDB = "dbname";
// connection to the SQL Server
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT col01, col02, col03, col04, col05, col06, col07 ";
$query .= "FROM table ";
$result = mssql_query($query, $dbhandle);
//Generate CSV file - Set as MSSQL_ASSOC as you don't need the numeric values.
while ($l = mssql_fetch_array($result, MSSQL_ASSOC)) {
foreach($l AS $key => $value){
//If the character " exists, then escape it, otherwise the csv file will be invalid.
$pos = strpos($value, '"');
if ($pos !== false) {
$value = str_replace('"', '\"', $value);
}
$out .= '"'.$value.'",';
}
$out .= "\n";
}
//free result set memory
mssql_free_result($result);
//close the connection
mssql_close($dbhandle);
// Output to browser with the CSV mime type
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=export.csv");
echo $out;
?>
Use http://php.net/manual/en/function.mssql-fetch-field.php , like this:
http://www.razorsql.com/articles/sqlserver_column_names_values.html
Adding col01, col02, col03, col04, col05, col06, col07 to the first line of your $out variable before iterating through you request results will solve your problem
out .="col01, col02, col03, col04, col05, col06, col07\n"