【问题标题】:How to create a file upload form that creates more form fields based on input using php?如何创建一个文件上传表单,该表单基于使用 php 的输入创建更多表单字段?
【发布时间】:2011-09-08 14:56:49
【问题描述】:

我的 SQL 表中有十列:id、imgid、urlid、image1、image2、image3、image4、image5 和 comment。 Id、imgid 和 urlid 是 int 类型。图像[1-5] 是中等大小的类型。 Url 和comment 是文本类型。 imgid 是上传的图片数量(最大应该是 5),urlid 是提交的 url 数量(现在应该是一个),url 保存 url,comment 保存用户 cmets。

表单首先询问用户他想上传多少张图片(我的脚本中最多为 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>

【问题讨论】:

  • 呃,又是意大利面条代码。人们真的必须使用 MVC..
  • 同意,你真的可能想重新考虑你的方法。
  • 你为什么用php而不是javascript做这个?

标签: php forms file loops upload


【解决方案1】:

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

使用 IDE 编辑脚本,以避免此类愚蠢的错误。试试 NetBeans、PhpStorm。
并尝试阅读MVC。

【讨论】:

  • 感谢您的帮助。我基本上是在尝试使用 youtube 教程、谷歌搜索、W3schools 和这个网站尽可能快地填充 PHP,所以对我来说似乎是一个愚蠢的错误并不那么明显。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
相关资源
最近更新 更多