批量读取文件名存入MySQL是一项常见的任务,我们可以通过PHP语言来实现。
首先,我们需要遍历指定目录下的所有文件,可以使用PHP的scandir函数来实现:
$dir = "/path/to/directory";
$files = scandir($dir);
接下来,我们需要连接到MySQL数据库,并创建一个表来存储文件名:
$conn = mysqli_connect("localhost", "username", "password", "database");
$sql = "CREATE TABLE IF NOT EXISTS files (
id INT(11) NOT NULL AUTO_INCREMENT,
filename VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
)";
mysqli_query($conn, $sql);
然后,我们可以使用foreach循环遍历$files数组,并将文件名插入到MySQL表中:
foreach ($files as $file) {
if ($file == "." || $file == "..") continue;
$filename = mysqli_real_escape_string($conn, $file);
mysqli_query($conn, "INSERT INTO files (filename) VALUES ('$filename')");
}
最后,不要忘记关闭数据库连接:
mysqli_close($conn);
完整的代码如下:
$dir = "/path/to/directory";
$files = scandir($dir);
$conn = mysqli_connect("localhost", "username", "password", "database");
$sql = "CREATE TABLE IF NOT EXISTS files (
id INT(11) NOT NULL AUTO_INCREMENT,
filename VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
)";
mysqli_query($conn, $sql);
foreach ($files as $file) {
if ($file == "." || $file == "..") continue;
$filename = mysqli_real_escape_string($conn, $file);
mysqli_query($conn, "INSERT INTO files (filename) VALUES ('$filename')");
}
mysqli_close($conn);