基于数组插入表

时间:2015-01-12 13:46:40

标签: php mysql

我有一个文件名数组

$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.
    }   
}

我想在每个文件名的项目表中插入一条新记录,例如

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;
}

但是现在对数据库有影响。

1 个答案:

答案 0 :(得分:2)

文件名是字符串所以它应该在引号中关闭,并且根据你的代码它是打开的,所以在文件名周围加上引号并且不要为id传递NULL,如果它是自动的增量字段相应地增加增量值。

更改您的查询
$query = "INSERT INTO `projects` (`id`, `name`) VALUES (NULL,$filename)";

$query = "INSERT INTO `projects` (`name`) VALUES ('".$filename."')";