To connect to a database and import an SQL file in PHP, you can use the MySQLi extension. Here is a simple example of code that demonstrates how to connect to a database and execute an SQL file:
// 配置数据库连接信息
$host = "localhost"; // 数据库主机名
$user = "username"; // 数据库用户名
$password = "password"; // 数据库密码
$dbname = "database_name"; // 数据库名称
// 创建数据库连接
$conn = mysqli_connect($host, $user, $password, $dbname);
// 检查连接是否成功
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
// 读取 SQL 文件内容
$sql = file_get_contents("path/to/file.sql");
// 执行 SQL 文件内容
if (mysqli_multi_query($conn, $sql)) {
echo "SQL 文件导入成功!";
} else {
echo "导入失败: " . mysqli_error($conn);
}
// 关闭数据库连接
mysqli_close($conn);In the above code, we first configure the database connection details, then use the mysqli_connect() function to establish a database connection. Next, we use the file_get_contents() function to read the contents of the SQL file and then use the mysqli_multi_query() function to execute multiple SQL statements contained within that file. Finally, we close the database connection.
Please note that the above code is only applicable when the SQL file contains multiple SQL statements. If your SQL file contains only a single SQL statement, you can use the mysqli_query() function to execute that statement.