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

Asked

Viewed 263 times

0

I am working on a php on localhost where from the root folder will be to read all files and folders and insert into a MYSQL database but I’m having a hard time Can someone help us? 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('../'); ?>

1 answer

1

The code

I redid all the code, but oriented to objects and using PDO (PHP Data Object) I tested the code and it is working perfectly. How I used your database data 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 from the css directory just run the following code:

fromFolderToDB('css');

Any questions ask for comments.

  • for the time being from the following error: SQLSTATE[HY000] [2002] No connection could be made because the target computer actively refused them.

  • I have one that gave but does not have path url so shows file:

  • This error (SQLSTATE[HY000] [2002]) occurs because Mysql is not enabled. If you use Xampp just go to Control Panel and activate it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.