gpt4 book ai didi

php - 使用 php 将 sql 文件导入远程 mysql 数据库

转载 作者:行者123 更新时间:2023-11-29 21:40:04 26 4
gpt4 key购买 nike

php 和 mysql 新手,我正在尝试将导出的 sql 文件插入远程数据库。我正在尝试来自 1and1 的代码但它不起作用。

$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,我有另一种方法可以做到这一点,试试这个

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

?>

希望这对您有帮助。 :)

注意:不推荐使用 mysql,相反,您可以使用 Mysqli、PDO,如下所示。

$db = new PDO($mysql_host, $mysql_username, $mysql_password);

$sql = file_get_contents('churc.sql');

$qr = $db->exec($sql);

对于执行大的sql文件,我上面的答案是不够的,所以我建议你看看@Abu Sadat答案here

关于php - 使用 php 将 sql 文件导入远程 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34604527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com