Algorithm isn't working

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hey guys,

I seem to be having a problem with part of my code.  This code is
supposed to connect to a database and perform a query to get all the
name fields in all the records.  The program then compares the results
to the file names of all the files in a certain directory.  I'm doing
this so I will know if another record needs to be added.
Unfortunately, the algorithm I am using does not work.  I can't seem to
find what is wrong with it.  Instead of the giving me the next file
name that needs to be added, it gives me the last file name that I have
already added.

Here is the code:
      $files = scandir("c:\apache2triad\htdocs\pictures");
      $numberElements = count($files);

      // Connect to the server and select the database
      @mysql_connect("localhost", "user", "password")
          or die("Could not connect to MySQL server!");
      @mysql_select_db("website") or die("Could not select database!");

      // process query
      $query = "SELECT name FROM pictures WHERE 1";
      $result = mysql_query($query);

      if(!$result) echo "Error processing query!";

      // find number of rows returned in the result of query
      $numberRows = mysql_numrows($result);

      // compare query results with file names
      for( $rowNumber = $numberRows; $rowNumber > 0; $rowNumber-- )
          $exists = false;
          $name = mysql_result( $result, $rowNumber - 1, name );
          for( $elementNumber = $numberElements; $elementNumber > 0;
$elementNumber-- )
              if( $files[elementNumber - 1] == $name )
                  $exists = true;
          if( $exists == false )
              echo "File $name needs to be added to the database!";

Can you help me?

Re: Algorithm isn't working

On 10-Jul-2005, wrote:

Quoted text here. Click to load it

The break needs to be in the if block inside the inner for loop. There may
be more problems, but that's what jumped out at me.

Tom Thackrey
tom (at) creative (dash) light (dot) com
do NOT send email to (it's reserved for spammers)

Re: Algorithm isn't working

Quoted text here. Click to load it

What makes you so certain that the order in the $files array corresponds  
one-to-one with the result of the query?  Also, you say that you want to add  
a record (to the DB) if the file is not there.  Yet, you are only searching  
over the records in the DB and not over the files you have from scandir.  It  
seems the opposite of what you want.

I think you should first query the database as you do and build an array of  
names from there.  Then you should loop over the files in the array you  
obtain from scandir.  For each loop you should check for its presence in the  
array from the query.  If it is not there, then add it.


Site Timeline