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
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";
?>
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 = '';
}
}
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 have the following php code:
<?php
$hostname="db.";
$database="db..";
$username="db...";
$password="pw...";
$mysql = mysql_connect($hostname, $username, $password);
if(!$mysql)
echo 'Not conneted to the database...' . mysql_error() ;
else
echo 'Connected to the database...' ;
// select the appropriate database
$mysqldb = mysql_select_db( $database );
if(!$mysqldb)
die('Could not select the database...' . mysql_error());
else
echo '<br /><br />Connected to database...<br /><br />' ;
$chk_table_access = 'select * from table_name where 1';
$chk_access = mysql_query($chk_table_access);
echo $chk_table_access . '<br /><br />';
if (!$chk_access)
echo 'Could not access table: ' . mysql_error() ;
else
echo 'Table was accessed..<br /><br />' ;
$backup = 'SELECT * INTO OUTFILE "result.csv" FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY ';
$backup = $backup . "'" . '"' . "'" ;
$backup = $backup . ' FROM cities WHERE 1';
echo $backup . '<br /><br />';
$bk_success = mysql_query($backup);
if (!$bk_success)
echo 'The backup was not successful. Reason: ' . mysql_error();
?>
The program runs fine on localhost, but when I run it from my web site I get the following error: Access denied for user 'dbo????????'#'%' (using password: YES). The web help is not much help.
I do get the "Table was accessed.." message so I'm accessing the table okay. I do frwite to the directory every day without errors. I understand why it doesn't work in phpMyAdmin. I'm a little stumped. It's also the first question I've asked on this forum although I come here often for help. You guys (ladies included) rock.
Thanks in advance,
Steve
Your MySQL user apparently lacks the FILE privilege.
Does the MySQL server run on the same machine as the web server? If both servers run on different machines, you can stop right here: Even with FILE privilege, the output file would be created on the database server (and would probably inaccessible from the web server).