将多个图像名称插入到相同的数据库字段中,以逗号分隔

时间:2014-10-08 14:16:00

标签: php mysql image-uploading

我有这个脚本:

上传多个文件 - 代码片段

foreach ($_FILES['files']['name'] as $f => $name) {    

    if ($_FILES['files']['error'][$f] == 0) {              
    } 

    else{ // No error found! Move uploaded files 
        $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
        $uniq_name = uniqid() . '.' .$ext;
        $dest = $path . $uniq_name; //FULL DESTINATION
        if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)) {
            $count++;   
        }
    }
}

请告诉我如何将所有照片名称插入我的mysql数据库,在PHOTOS字段中用逗号分隔。

当我写2行代码时:

$a = "INSERT INTO dbu.dbu_data(photos) VALUES ('$uniq_name')";
mysql_query($a);

它为每张上传的照片插入表格行,我不想这样做。

1 个答案:

答案 0 :(得分:1)

$delimiter = ",";
$str = '';

foreach ($_FILES['files']['name'] as $f => $name) {

    if ($_FILES['files']['error'][$f] == 0) {

        // surely your move logic needs to go here

    } else{ // No error found! Move uploaded files
        $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
        $uniq_name = uniqid() . '.' .$ext;
        $dest = $path . $uniq_name; //FULL DESTINATION
        if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)) {
            $count++;

            if (strlen($str)) {
                $str .= $delimiter;
            }

            $str .= $dest;

        }
    }

}

if (strlen($str)){

    $a = "INSERT INTO dbu.dbu_data(photos) VALUES ('" . mysql_real_escape_string($str) . "')";
    mysql_query($a);

}