Page 1 of 1

test mysql_query result

Posted: Sat Jun 27, 2009 12:40 pm
by ThaJock
I am trying to write a script that does the following:

1. Loop through my audio folder which contains the following four files:
I'll Be Right Here.mp3
Time Marches On.mp3
Where Did It Go (Our Love).mp3
You're Still The One.mp3

2. Check for .mp3 file extension

3. Query table to see if the file name as string exists in my table(the audio table is empty)
_If not then insert the file name into the table.

Here is my code:

Code: Select all

<?php
include("connect.php");
if ($handle = opendir("audio")) {
    while (false !== ($file = readdir($handle))) {
        
        $checker = end(explode('.', $file));
        if($checker=='mp3'){
            Update($file);
        }
    }
    closedir($handle);
}
 
function Update($audio){
    $result = mysql_query("SELECT * FROM audio WHERE name = '$audio'");
    if(!$result){
        echo $audio."</br>";
        //mysql_query("INSERT INTO audio (name) VALUES ('$audio')");
    }
}
?>
Everything seems to work fine except it only echos these two files:
I'll Be Right Here.mp3
You're Still The One.mp3

If anyone can help me understand why the other 2 strings are not being echoed I would appreciate it.

Re: test mysql_query result

Posted: Sat Jun 27, 2009 12:44 pm
by danielrs1
Replace the line:

Code: Select all

$result = mysql_query("SELECT * FROM audio WHERE name = '$audio'");
With this:

Code: Select all

$result = mysql_query("SELECT * FROM audio WHERE name = '".mysql_real_escape_string($audio)."'");

Re: test mysql_query result

Posted: Sat Jun 27, 2009 12:52 pm
by requinix
Don't forget to do it with the INSERT too.

Code: Select all

if(!$result){
$result will only tell you if the query was valid - not whether it returned results.

Code: Select all

$result = mysql_query("SELECT * FROM audio WHERE name = '$audio'");
if($result && mysql_num_rows($result) == 0) {

Re: test mysql_query result

Posted: Sat Jun 27, 2009 1:00 pm
by danielrs1
lol I forgot that. If you only make the replacement I suggested, then you'd get no results.

The code you should use is:

Code: Select all

<?php
include("connect.php");
if ($handle = opendir("audio")) {
  while (false !== ($file = readdir($handle))) {
    
     $checker = end(explode('.', $file));
    if($checker=='mp3'){
      Update($file);
    }
  }
 closedir($handle);
}
 
function Update($audio){
  $result = mysql_query("SELECT * FROM audio WHERE name = '".mysql_real_escape_string($audio)."'");
  if($result && mysql_num_rows($result) == 0){
    echo $audio."</br>";
    //mysql_query("INSERT INTO audio (name) VALUES ('$audio')");
  }
}
?>

Re: test mysql_query result

Posted: Sat Jun 27, 2009 1:20 pm
by ThaJock
Thank you guys so much for your help. I am new to php and really only know some of the basics. I am very happy that I joined this community. The turn around time is amazing.

I'm going to study what you guys have shown me in this post and learn from it. Thanks again for your help.