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.

3
  • 1
    $filename that is most likely going to be a string; quote it. Commented Jan 12, 2015 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 Commented Jan 12, 2015 at 13:48
  • 1
    See also Why shouldn't I use mysql_*() functions. Instead of writing new code with the deprecated API, this is a great time to start learning to use PDO, which supports prepared statements (avoiding quoting issues like this) and improving security. Commented Jan 12, 2015 at 13:51

1 Answer 1

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."')";
Sign up to request clarification or add additional context in comments.

1 Comment

Personally, I like to give an explanation as to why something should be done a certain way, including why code fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.