插入表单和多个上传

时间:2015-03-20 18:46:16

标签: php html mysql upload

我想插入广告。广告包含标题,一些文本,价格并且可以具有一个或多个图像。表格全部在一页上。 php和html也在一个文件中。

在我的数据库中,我有一个advertisement表和一个image表。他们都有一个独特的身份证作为主要。

image表还包含来自filename的{​​{1}}和advertisement_id,它是该表的外键。

问题:

  1. 如何上传多个文件?

  2. 我是否需要立即插入everthing或先插入广告然后再插入图片?

  3. advertisement table

1 个答案:

答案 0 :(得分:0)

至于你的第二个问题,我认为插入广告然后插入所有图片会更明智。

关于第一个问题,

html代码就是那样的

    <form name="multiupload" action="uploadmany.php" method="post" enctype="multipart/form-data">
    <input name="filesToUpload[]" type="file" multiple /></td>
    <td collapse=2><input name="savemultiimg" type="submit" value="submit"></td>
    </form>

这是php代码。变量$err是上传状态的通知。

    <?php
require("DataBaseConnection.php");
if(isset($_POST["savemultiimg"])) {
    for($i=0;$i<count($_FILES['filesToUpload']['tmp_name']);$i++){
        $name=$_FILES['filesToUpload']['name'][$i];
        $tmp_name=$_FILES['filesToUpload']['tmp_name'][$i];


$target_dir = "images/";  //the dir where you want to save images
$target_file = $target_dir . rand().'_'.($name); //this will be the name of the img, and we will give it a random number so if you uploaded two image with same name you don't have a problem
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
    $check = getimagesize($tmp_name);
    if($check !== false) {
        //echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        $err= "file you uploaded is not an image";
        $uploadOk = 0;
    }//end if

// Check if file already exists,, this will appear if you removed the random number on the top
if (file_exists($target_file)) {
    $err ="file already exists";
    $uploadOk = 0;
}//end if

if ($uploadOk != 0)
{
if (move_uploaded_file($tmp_name, $target_file)) {
    $err ="file uploaded succ.";
    $sql = "...";//your sql here
    $result = $con->query($sql);

} else {
    $err ="unecpected error occured";
}   //end if upload

    }//end ($uploadOk != 0)
}//end forloop
header('Location: index.php?err='.$err.');
}
?>

这段代码来自我的一个大学项目,我刚刚修改它以告诉你。如果它给你带来任何错误,请告诉我,我很乐意帮助你。

原始代码是从w3schools复制的,并且对多次上传进行了更改。