PHP + mysql - insert mysql based all file name and path

0

I'm working on a php on localhost where from the root folder it will be to read all the files and folders and insert into a MYSQL based but I'm having difficulties Can someone help? obrgd;)




/*CONNECT DB */
$link = mysqli_connect("localhost", "root", "usbw", "beifaserver") or die("Error " . mysqli_error($link));


mysqli_query($link,"delete from search"); 
/*CLEAN DB TABLE*/


function listFolderFiles($dir){  /*READ DIR/ File*/
    $ffs = scandir($dir);
    echo '';
    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            echo '';
            if(is_dir($dir.'/'.$ff)){
                echo $ff;
                listFolderFiles($dir.'/'.$ff);

            }
            else{
                echo ''.$ff.'';
                $try = mysqli_query($link,"INSERT INTO search (title,url, dategrab)VALUES ('".$ff."', '".$dir."/".$ff."', '".date('2004-m-d H:i:s')."')");
                    if($try === false){
                    echo 'error - ';
                    echo mysqli_error($link);
                }
            }
            echo '';
        }
    }
    echo '';
}


listFolderFiles('../');

?>
    
asked by anonymous 31.05.2014 / 15:31

1 answer

1

The code

I have refactored all the code, however object oriented and using PDO (PHP Data Object) I have tested the code and it is working perfectly. How I used the data from your database just run the code. I also changed the function name to fromFolderToDB .

<?php
try {
    $pdo = new PDO('mysql:server=localhost;dbname=beifaserver', 'root', 'usbw');
} catch ( PDOException $e ) {
    echo $e->getMessage();
    exit;
}

function fromFolderToDB ($path) {
    global $pdo;

    foreach ( new DirectoryIterator($path) as $file ) {
        if ( !$file->isDot() ) {
            $date = new DateTime();

            $fileName = $file->getFileName();
            $filePath = $path . $fileName;
            $dateGrab = $date->format('2004-m-d H:i:s');

            $sth = $pdo->prepare("INSERT INTO 'search' ('title', 'url', 'dategrab') VALUES ('${fileName}', '${filePath}', '${dateGrab}')");
            $sth->execute();
        }
    }
}
Examples

If you want to, for example, add all the files in the css directory, just run the following code:

fromFolderToDB('css');

Any questions informs you about the comments.

    
31.05.2014 / 16:42