用于多图像上传到sql DB的循环

时间:2011-01-27 03:54:40

标签: php sql

我已编辑此代码,从1图像上传到2,但它很难看 - 基本上只是复制了以前的变量。我想要获得最多8个图像,并想象有一种方法可以创建一个数组并将其放入循环中,而不是为每个图像创建一个单独的实例。

感谢您的任何见解......

到目前为止,这是我的代码:

<?PHP 

include("inc/header.php");

$back = "<a href='sell.php'>Click Here To Go Back And Try Again</a>";

if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0 || $_FILES['userfile2']['size'] > 0 )
{

$title = $_POST['title'];  
$description = $_POST['description'];   
$category = $_POST['category'];  
$price = $_POST['price'];  
$name = $_POST['name'];  
$number = $_POST['number'];  
$email = $_POST['email'];  
$password = $_POST['password'];    


// PICTURE UPLOAD SYSTEM

 $imagename = basename($_FILES['userfile']['name']);  
 $imagename2 = basename($_FILES['userfile2']['name']);


if(empty($imagename) || empty($imagename2)) {  
$error = 1;  
echo"<h2 class='error'>The name of the image was not found.</h2>".$back;  
}

if($error != 1 && $noimg != 1)  
{

        $filename = stripslashes($_FILES['userfile']['name']);
        $extension = substr(strrchr($filename, '.'), 1);
       $extension = strtolower($extension);

        $filename2 = stripslashes($_FILES['userfile2']['name']);
        $extension2 = substr(strrchr($filename2, '.'), 1);
       $extension2 = strtolower($extension2);

//if it is not a known extension, we will suppose it is an error and will not  upload the file,  
//otherwise we will do more tests
    }

 if (($extension != "jpg") && ($extension2 != "jpg") && ($extension != "jpeg") && ($extension != "jpeg") && ($extension != "png") && ($extension2 != "png") && ($extension != "gif") && ($extension2 != "gif"))   
        {  
        //print error message  
            echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>'.$back.'';  
            $errors=1;   
        }  
        else  
        {  
$time = time();
$newimage = "photos/" . $time . $imagename;
$newimage2 = "photos/" . $time . $imagename2;

$result = @move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);  
$result2 = @move_uploaded_file($_FILES['userfile2']['tmp_name'], $newimage2);  
if(empty($result)) {  
$error = 1;  
echo "<h2 class='error'>There was an error moving the uploaded file.</h2><br/>".$back."";   
}

// insert to SQL

$date = date("Y-m-d G:i:s");   
$query = "INSERT INTO classifieds (adid, title, description, cat, price, name, number, email, password, picture, picture2, date, views, authorized ) VALUES ('', '$title', '$description', '$category', '$price', '$name', '$number', '$email', '$password', '$newimage', '$newimage2', '$date', '0', '0')";  
mysql_query($query) or die(mysql_error());

}

2 个答案:

答案 0 :(得分:1)

如果使用

强制输入数组
<input type='file' name='file[]' />
<input type='file' name='file[]' />
<input type='file' name='file[]' />

然后使用我在file-upload.multiple.php

中找到的以下功能
function reArrayFiles(&$file_post) {
    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }
    return $file_ary;
}

您将能够非常轻松地遍历数组,几乎没有注意到您处理多个文件。

if (isset ($_POST['upload'])) {
    extract ($_POST, EXTR_PREFIX_ALL, 'post');

    $file_ary = reArrayFiles ($_FILES['file']);

    $error = 0;
    foreach ($file_ary as $file) {
        // Test a file is uploaded for each input
        if ($file['size'] == 0 || empty ($file['name'])) {
            $error = 1;
            break;
            // Note: If not all input slots are required to be filled,
            //       replace the above with:
            //           continue;
            //       This will stop running this step of the loop here 
            //       and start the next one.
        }
        // Test file format
        if (!in_array ($file['type'], array (
                'image/jpg',  'image/png',
                'image/jpeg', 'image/gif')) {
            $error = 2;
            break;
        }
    }

    if (!$error) { // True is returned if value is not 0;
        $newpath = 'photos/'.time();
        foreach ($file_ary as $file) {
            $res = @move_uploaded_file($file['tmp_name'], 
                    $newpath.'-'.$file['name']);
            unlink ($file['tmp_name']);
            if (!$res) {
                $error = 3;
                break;
            }
        }
    }

    if (!$error) {
        $res = mysql_query(' ... insert query ... ');
        if (!$res) {
            $error = 4;
        }
    }

    if ($error) {
        // If you wanted to be super thorough, you could loop through 
        // and make sure that if any files did get moved that they 
        // were deleted.
        $msg = "";
        switch ($error) {
            case 1: $msg = 'File not found.'; break;
            case 2: $msg = 'Incorrect file format.'; break;
            case 3: $msg = 'Error moving uploaded file.'; break;
            case 4: $msg = 'Database query failed. '.mysql_error(); break;
            default: $msg = 'Error';
        }
        echo "<h2 class='error'>$msg</h2><a href='sell.php'>Try Again.</a>";
    }
}

答案 1 :(得分:0)

结帐:http://www.php.net/manual/en/features.file-upload.multiple.php

我过去做过的一种硬编码方式是:

<input type="file" name="file_1" />
<input type="file" name="file_2" />
<input type="file" name="file_3" />

然后提交时:

foreach($_FILES as $file) {
     // file actions
}