使用PHP

时间:2016-04-18 22:30:00

标签: php

初学者PHP编码器。我编写了这段代码来遍历目录并捕获一些数据,然后使用该数据来更新数据库。

<?php

$servername = "localhost";
$username = "popcorn";
$password = "**********";
$dbname = "professional_test123";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$path = "/home/professional/www/dan/myFiles";
if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

$title = pathinfo($file,PATHINFO_BASENAME);
$size = filesize($file);
$myFile[$title]['size'] = filesize($file);

$sql = "UPDATE Files SET Size = '$size' WHERE Name = '$title'";
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

}
closedir($handle);
$conn->close();

我现在要做的是遍历根目录中的许多子目录,并从所有子目录中收集相同的数据。我读到我可以将RecursiveDirectoryIterator与RecursiveIteratorIterator结合使用来完成此操作,但我不确定如何将它合并到我的代码中。非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

这是一个开始 - 一个递归函数,如果它遇到一个文件夹就调用它自己,或者如果它遇到一个文件就运行你的db查询。 $ myFile通过引用传入,因此允许该函数动态地向其添加新项,而无需从函数中返回值。

$myFile = array();
$path = "/home/professional/www/dan/myFiles";
updateSize($path, $myFile);

function updateSize($path, &$myFile){
    if ($handle = opendir($path)) {
        while (false !== ($file = readdir($handle))) {
            if ('.' === $file) continue;
            if ('..' === $file) continue;

            $full_path = $path.'/'.$file;

            if(is_dir($full_path)){
                //function calls itself
                updateSize($full_path, $myFile); 
            } else {
                $title = pathinfo($file, PATHINFO_BASENAME);                
                $size = filesize($full_path);
                $myFile[$title]['size'] = $size;

                $sql = "UPDATE Files SET Size = '$size' WHERE Name = '$title'";
                if ($conn->query($sql) === TRUE) {
                    echo "Record updated successfully";
                } else {
                    echo "Error: " . $sql . "<br>" . $conn->error;
                }
            }
        }//while
    closedir($handle);
    }//if
}