我需要从我的PHP中运行一个SQL文件(以创建用户(。我知道这是怎么做到的:
$commands = file_get_contents("sql/create_usr.sql")
$commands = explode(";", $commands);
foreach($commands as $command){
if($command){
$success += (@mysql_query($command)==false ? 0 : 1);
$total += 1;
}
}
如何使用 PHP 文件中的特定参数(例如用户名、密码(运行 SQL 文件。提前谢谢。
您可能希望为此使用简单的 shell 执行,而不是使用 PHP 拆分文件:
shell_exec( 'mysql DATABASE -u USERNAME -pPASSWORD < sql/create_usr.sql' );
为了进行测试,如果您可以使用shell_exec
运行 SQL 查询,您可能需要尝试以下代码:
echo shell_exec( 'mysql DATABASE -u USERAME -pPASSWORD -e "SELECT DATABASE();" 2>&1' );
逐行读取文件并执行判决
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
}
} else {
// error opening the file.
}
fclose($handle);