0

I have an array of file names

$files = array();
$dirName = getcwd()."/../";
$dir = opendir('../'); // open the cwd..also do an err check.
while(false != ($file = readdir($dir))) {
    if(($file != ".") and ($file != "..") and ($file != "index.php")and ($file != "img") and ($file != "__MACOSX")) {
            $files[] = $file; // put in array.
    }   
}

I want to insert a new record into projects table for each filename e.g.

foreach($files as $file) {  
    $filename = mysql_real_escape_string($file);

    $query = "INSERT INTO `projects` (`id`, `name`) VALUES (NULL,$filename)";
    $result =  mysql_query($query, $connection);
    echo $result;
}

However has now effect on the database.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
lpoulter
  • 158
  • 9
  • 1
    `$filename` that is most likely going to be a string; quote it. – Funk Forty Niner Jan 12 '15 at 13:47
  • 1
    You need to check `mysql_error($connection)` to verify the result of this action. As @Fred-ii- said, the string $filename [will need to be single-quoted](http://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks) – Michael Berkowski Jan 12 '15 at 13:48
  • 1
    See also [Why shouldn't I use `mysql_*()` functions](https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). Instead of writing new code with the deprecated API, this is a great time to [start learning to use PDO](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers), which supports prepared statements (avoiding quoting issues like this) and improving security. – Michael Berkowski Jan 12 '15 at 13:51

1 Answers1

2

file name is string so it should be closed in quote and as per your code it's open so put quote around the file name and don't pass NULL for id, if it's auto increment field than it will add incremented value accordingly.

change your query from

$query = "INSERT INTO `projects` (`id`, `name`) VALUES (NULL,$filename)";

to

$query = "INSERT INTO `projects` (`name`) VALUES ('".$filename."')";
Ram Sharma
  • 8,676
  • 7
  • 43
  • 56