如何创建一个文件上传表单,使用php根据输入创建更多表单字段


How to create a file upload form that creates more form fields based on input using php?

我的SQL表中有十列:id、imgid、urlid、image1、image2、image3、image4、image5和comment。Id、imgid和urlid是int类型。图像[1-5]为中等斑点类型。Url和注释为文本类型。Imgid是上传的图像数量(最大值应为5),urlid是提交的url数量(现在应为一),url包含url,comment包含用户评论。

表单首先询问用户他想上传多少张图片(在我的脚本中,最大数字是5)。例如,如果用户选择了3个,那么也应该使用新的提交按钮创建3个文件上传字段。一个名为$imgid的变量将存储数字3,这是用户想要上传的文件数量。然后,用户选择3个图像,并单击新创建的提交按钮,将这三个图像提交到SQL表中的前三个图像列中。我的问题是,当我点击第一个按钮后出现的第二个提交按钮时,我会得到这个错误:

Warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty in dbpform2.php on line 75

以下是我迄今为止所做的:

<html>
<body>
<form action="dbpform2.php" method="POST">
How many images do you want to upload?<br>
<input type="text" name="imgid"  /><br />
<input type="submit" name="submit" value="submit" />
</form>
<?php 
mysql_connect ("","","") or die(mysql_error());
mysql_select_db ("") or die(mysql_error());

$imgid = $_POST['imgid'];
if (isset($_POST['submit']))
{
    echo"<form action='dbpform2.php' method='POST' enctype='multipart/form-data'>
";
    if ($imgid >= 5)
    {
        for ($i=1; $i<= 5; $i++)
        {
        ${'img' . $i} = "img".$i;
        echo "<input type='file' name='${'img' . $i}'  /> <br />";
        }
        echo"
        <input type='hidden' name='imgid' value='$imgid' />
        <input type='submit' name='submit2' value='submit2' />
        </form>";
    }
    if ($imgid <= 5)
    {
        for ($i=1; $i<=$imgid; $i++)
        {
        ${'img' . $i} = "img".$i;
        echo "<input type='file' name='${'img' . $i}'  /> <br />";
        }
        echo"
        <input type='hidden' name='imgid' value='$imgid' />
        <input type='submit' name='submit2' value='submit2' />
        </form>";
    }
}
?>
<?php
$imgid = $_POST['imgid'];
for ($i=1; $i <= $imgid; $i++)
{
${'img' . $i} = "img".$i;
${'file' . $i}  = $_FILES['${'.img.' . $i}']['tmp_name'];
}
    if (isset($_POST['submit2']))
    {
        for ($i=1; $i<=$imgid; $i++)
        {
            ${'img' . $i} = "img".$i;
            ${'file' . $i} = addslashes(file_get_contents ($_FILES['${'.img.' . $i}']['tmp_name']));
        }
        mysql_query ("INSERT INTO dbp VALUES ('','$imgid','$urlid','$url', '$file1', '$file2','$file3','$file4','$file5','$comment')"); 
    }
?>

</body>
</html>

$_FILES['${'.img.' . $i}']
替换为
$_FILES[${'img' . $i}]

使用IDE来编辑脚本,以避免此类愚蠢的错误。试试NetBeans,PhpStorm
试着阅读一下MVC。