0

I have some files on my server that I want to put into a database. I'll add some more information such as comments about the files (the SQL query for the files will be easier to compare with the database after I have fixed this problem) to the database and also to save some bandwidth. The thing is that I want to see if the folders/files already exists in the database. If not, add them to the database.

Here's how my code looks like at the moment (sql() is a function I have created) (the code below only echos the names of the existed names in the database for development purposes):

$dir = new RecursiveDirectoryIterator($admin['data_folder_main'], FilesystemIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
$it->setMaxDepth(1);

foreach($it AS $fileinfo) {

    # DATABASE (fetch)
    $folder = sql("SELECT *
                   FROM items_folders
                   WHERE name_folder = :folder
                  ", Array('folder' => $it->getSubPath()), 'fetch');


    echo $folder['name_folder'].'<br>';

}

And here's how the database looks like:

CREATE TABLE IF NOT EXISTS `items_folders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_folder` int(11) NOT NULL DEFAULT '0',
  `name_folder` text NOT NULL,
  `name_folder_sub` text NOT NULL,
  PRIMARY KEY (`id`)
)

The problem is that the code above prints the existed name from the database and then echos the name same amount of times as it is folders/files in the folder on the server. Here's how I want it: does the folder exists in the database? Yes or no.

Yes? Good! Ignore it (don't add it to the database). Moving on to the next folder/file (if there is any).

No? Add it to the database. Moving on to the next folder/file (if there is any).

How can I make this possible?

Airikr
  • 5,214
  • 12
  • 50
  • 100

2 Answers2

0

You simply need to test for whether there is a value and if not, add the item to the database

foreach($it AS $fileinfo) {

    # DATABASE (fetch)
    $folder = sql("SELECT *
                   FROM items_folders
                   WHERE name_folder = :folder
                  ", Array('folder' => $it->getSubPath()), 'fetch');


   //test to see if there is a value in the database
      if($folder['name_folder']==''){
          // if not, add it
          strSQL = "UPDATE items_folders SET name_folder='". $folder['name_folder'] . "' WHERE id= ". $folder['id'];
         //you don't tell us if you are using PDO or mysql_ so do your own execution
         execute;
         echo "item added";
      }
}

Not tested, but it gives you an idea of what to do.

Steve
  • 1,195
  • 1
  • 14
  • 34
  • Notice syntax highlighting, how it's off? I think it's this line `WHERE id= ". $folder['id']"` which needs to be `WHERE id= '". $folder['id']"'` – Funk Forty Niner Feb 20 '14 at 00:26
  • Thanks, but you need to give people a minute or so after they post to edit. – Steve Feb 20 '14 at 00:26
  • Sorry, just trying to avoid someone else to potentially downvote you. I don't do that, it's not my style, but there are some out there that do just that and take pleasure in doing it too. ;-) – Funk Forty Niner Feb 20 '14 at 00:27
  • np, and if the OP uses my code as is without checking or modifying it, more fool them :o) – Steve Feb 20 '14 at 00:28
  • 1
    True. The OP will get the general idea. However, it's good practice to write pseudo-code that is in fact workable code also. SO's syntax highlighting is a dead giveaway and some may not know what to do with it, in thinking "hey, it must be good, it's an answer". We don't know other people's abilities/knowledge. ;-) You know, and I know, but others probably may not (maybe even the OP). Just trying to help and cover all the bases. – Funk Forty Niner Feb 20 '14 at 00:30
  • What I generally do to "feel them out, *as it were*" is post a comment in laying out the general groundwork (*as you may have already seen*). Then, if I gained the OP's curiousity and needs further info/help, then that's when I (might) put in an answer. That's just "me". ;-) (and it keeps the tire-kickers away). – Funk Forty Niner Feb 20 '14 at 00:33
0

If you use

" SELECT CAST(COUNT(*) AS BIT) AS existing FROM items_folders WHERE name_folder = :folder"

you should get an boolean return value (true or 1 if it exists).

"SELECT DISTINCT * FROM items_folders WHERE name_folder = :folder"

removes all double values and if you want to instert a folder if it not exists use:

"[Insert-Statement] WHERE NOT EXISTS (SELECT * FROM items_folders WHERE name_folder = :folder)"

nidomiro
  • 762
  • 1
  • 8
  • 24
  • Thanks but I'm getting this error message when I try your solution: `Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EXISTS( SELECT * FROM items_folders WHERE name_folder = '')' at line 1' in ...` – Airikr Feb 20 '14 at 00:36
  • That's because you need to bind your values. You are using `bindParam` or `bindValue`, right? @ErikEdgren – Funk Forty Niner Feb 20 '14 at 00:41
  • then try do add Select before Exists – nidomiro Feb 20 '14 at 00:43
  • **Fred-ii-**: Na. I don't use `bindParam` or `bindValue` but I might will do that :) **niccomatik**: That didn't work either - same error – Airikr Feb 20 '14 at 00:50
  • @niccomatik I am afraid not :( `Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BIT) FROM items_folders WHERE name_folder = 'test-folder'' at line 1' in ...`. I changed `'fetch'` to `'count'` since `COUNT(*)` is in that query – Airikr Feb 20 '14 at 00:55
  • I don't see fetch anywhere. The first sql statement returns one column with the name existing and one row with 0 (or false) or 1 (or true) – nidomiro Feb 20 '14 at 01:05
  • Please see the code in my question once again. On line 11 you'll see `'fetch'` at the end. If I use `SELECT *` then it will be `fetch`. If using `SELECT COUNT(*)` I'll use `count` instead. I have build my function like that. Your edit doesn't fix my problem about the error message :/ Same error as before. – Airikr Feb 20 '14 at 01:08