M
M
MSAFT2015-11-26 03:42:10
PHP
MSAFT, 2015-11-26 03:42:10

How to enter the names of all files from a folder into the database?

There is a small script that, as a result, should enter the name of all files from the specified folder into the MySQL database.
code snippet,

$directory = 'images/';
  $scandir = scandir($directory);


  for ($i=0; $i<count($scandir); $i++)

  {
    if ($scandir[$i] != '.' && $scandir[$i] != '..')

    {

      echo '<br><img width="50%" height="50%" src="'. $directory . $scandir[$i] . '" />';
      echo 'Название файла' . $scandir[$i] ;
    }

  }

   mysql_connect('localhost', 'root', '');
    $res = mysql_select_db('test'); 

    $sql = "INSERT INTO `people`(`id`, `name`, `deptId`) VALUES ('AUTO_INCREMENT', '" . $scandir[$i] . "', '3')";

    $res = mysql_query($sql);

I display variable arrays through the for loop, but only one line with an empty value is added in the name cell.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DevMan, 2015-11-26
@MSAFT

chewed mole!
long to explain, I'd better dance:

$directory = 'images/';

$files = glob($directory . '*');
$sql = '';
foreach ($files as $file) {
  if(is_dir($file)) {
    continue;
  }
  $sql .= '("' . $file . '", 3),';
}

$sql = 'INSERT INTO `people`(`name`, `deptId`) VALUES ' . substr($sql, 0, -1);
echo $sql;
I hope the meaning is clear.

S
Stalker_RED, 2015-11-26
@Stalker_RED

Check what exactly you are scanning. Do you really have this path?
$directory = 'images/';
You can use document_root or realpath and __FILE__.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question