Loading .SQL Files from Within PHP

Loading .sql files from within PHP

I'm getting the feeling that everyone here who's answered this question doesn't know what it's like to be a web application developer who allows people to install the application on their own servers. Shared hosting, especially, doesn't allow you to use SQL like the "LOAD DATA" query mentioned previously. Most shared hosts also don't allow you to use shell_exec.

Now, to answer the OP, your best bet is to just build out a PHP file that contains your queries in a variable and can just run them. If you're determined to parse .sql files, you should look into phpMyAdmin and get some ideas for getting data out of .sql files that way. Look around at other web applications that have installers and you'll see that, rather than use .sql files for their queries, they just package them up in PHP files and just run each string through mysql_query or whatever it is that they need to do.

How do I import a .sql file in mysql database using PHP?

Warning: mysql_* extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.

Whenever possible, importing a file to MySQL should be delegated to MySQL client.

I have got another way to do this, try this

<?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";
?>

This is working for me

Running MySQL *.sql files in PHP

This question comes up from time to time. There's no good solution for running a .sql script directly from PHP. There are edge cases where statements common in a .sql script can't be executed as SQL statements. For example, the mysql tool has builtin commands that are not recognized by the MySQL Server, e.g. CONNECT, TEE, STATUS, and DELIMITER.

So I give +1 to @Ignacio Vazquez-Abrams's answer. You should run your .sql script in PHP by invoking the mysql tool, for instance with shell_exec().


I got this test working:

$command = "mysql --user={$vals['db_user']} --password='{$vals['db_pass']}' "
. "-h {$vals['db_host']} -D {$vals['db_name']} < {$script_path}";

$output = shell_exec($command . '/shellexec.sql');

See also my answers to these related questions:

  • Loading .sql files from within PHP
  • is it possible to call a sql script from a stored procedure in another sql script?
  • PHP: multiple SQL queries in one mysql_query statement

PDO run script from .sql file

Since this is a script you can execute SQL with the following code:

try {
$mysql_host = "localhost";
$mysql_database = "planets_test";
$mysql_user = "root";
$mysql_password = "";
$dbh= new PDO("mysql:host=$mysql_host;dbname=$mysql_database", $mysql_user, $mysql_password);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = file_get_contents("planets_db.sql");
$dbh->exec($query);
print("Created $table Table.\n");

} catch(PDOException $e) {
echo $e->getMessage();//Remove or change message in production code
}

If there is an error it should tell you what went wrong.

how to import a .sql file using php function

It's working now!
Firstly, it didn't work in local server and secondly, instead of exec() function I used the system() function and finally, it generates a table in my database. Thanks everyone!

how to import .sql file in mysql databse with php

Try this code. You have to read the sql file first and than execute:

eg:

$sqlSource = file_get_contents('insert.sql');

mysqli_multi_query($sql,$sqlSource);

Error Reporting? Import .sql file from PHP and show errors

Try using shell_exec

$output = shell_exec( "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file" );
// parse $output here for errors

From the manual:

shell_exec — Execute command via shell and return the complete output as a string

Note:

This function is disabled when PHP is running in safe mode.

EDIT: Full solution:

what you need to do is grab STDERR and discard STDOUT. Do this by adding '2>&1 1> /dev/null' to the end of your command.

$output = shell_exec( "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file 2>&1 1> /dev/null" );
$lines = explode( PHP_EOL, $output );

$errors = array();

foreach( $lines as $line )
{
if ( strtolower( substr( $line, 0, 5 ) ) == 'error' )
{
$errors[] = $line;
}
}

if ( count( $errors ) )
{
echo PHP_EOL . 'Errors occurred during import.';
echo implode( PHP_EOL, $errors );
}
else
{
echo 'No Errors' . PHP_EOL;
}


Related Topics



Leave a reply



Submit