【问题标题】:How to store file name in database, with other info while uploading image to server using PHP?如何在使用 PHP 将图像上传到服务器时将文件名与其他信息一起存储在数据库中?
【发布时间】:2010-10-01 20:11:15
【问题描述】:

您好,我已经阅读了许多论坛和网站,这些论坛和网站告诉您如何将图像上传到服务器,并且我已经设法让它工作,我可以将文件上传到我的服务器,但存储文件名确实适用于以下我找到的示例,我还需要创建一个允许将更多数据输入数据库的表单。我坚持这一点,因为以前做过很多 PHP。我已经尝试了不同的网站教程,但没有取得多大成功,任何人都可以帮助我!我需要为我正在做的项目完成它。

我基本上是在尝试制作一个 CMS,它允许用户上传乐队成员的照片并存储有关他们的信息,以便将其显示在网页上供公众查看。


我的表是这样的:

Field              Type             Null    Default     
id                 int(10)          No                   
nameMember         varchar(25)      No                   
bandMember         text             No                   
photo              varchar(30)      No                   
aboutMember        text             No                   
otherBands         text             No      

我想要的表格是这样的:

   <h1>Adding a new Band Member or Affiliate</h1>
      <form method="post" action="addMember.php" enctype="multipart/form-data">
       <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Member's Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten!
            </p>
            <p>
              Photo:
            </p>
            <input type="file" name="filep" size=35 />
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" title="Add data to the Database" value="Add Member"/>
          </form>

上传图片到服务器的例子,也就是这样:

<?

if ($_POST["action"] == "Load")
{
$folder = "images/";

move_uploaded_file($_FILES["filep"]["tmp_name"] , "$folder".$_FILES["filep"]["name"]);

echo "
<p align=center>File ".$_FILES["filep"]["name"]."loaded...";

$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name

Error: " . mysql_error());

mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database

"; }

}

?>

我必须使用的示例表单是这样的:

<form action=addMember.php method=post enctype="multipart/form-data">
<table border="0" cellspacing="0" align=center cellpadding="3" bordercolor="#cccccc">
<tr>
<td>File:</td>
<td><input type="file" name="filep" size=45></td>
</tr>
<tr>
<td colspan=2><p align=center>
<input type=submit name=action value="Load">
</td>
</tr>
</table>
</form>

PS:图像文件已打开以供写入。

【问题讨论】:

  • 那应该是以前没做过多少php。对不起
  • 请不要使用以下示例中的mysql函数。它们已被弃用,应替换为 mysqli 类

标签: php mysql database image-processing file-upload


【解决方案1】:

这里是答案,供那些看起来像我在整个网络上试图找出如何完成这项任务的人使用。将照片上传到服务器,文件名存储在 mysql 数据库中,其他表单数据存储在数据库中。如果有帮助,请告诉我。

首先你需要的表格:

    <form method="post" action="addMember.php" enctype="multipart/form-data">
    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
          </form>

然后这段代码处理表单中的数据:

   <?php

// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;

// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?> 

代码编辑自www.about.com

【讨论】:

  • 如果你能根据文件名拆分方法将文件存储到各种目录中,那就太好了。 (这是在服务器需要处理大量数据的情况下)
【解决方案2】:

每张照片都有一个 ID,所以我的建议是重命名照片。例如你按日期重命名它

<?php
 $date = getdate();
 $name .= $date[hours];
 $name .= $date[minutes];
 $name .= $date[seconds];
 $name .= $date[year];
 $name .= $date[mon];
 $name .= $date[mday];
?>

注意:不要忘记文件的文件扩展名,或者您可以为照片生成随机字符串,但我不建议这样做。我还建议您在将文件上传到目录之前检查文件扩展名。

<?php 
if ((($_FILES["photo"]["type"] == "image/jpeg")
            || ($_FILES["photo"]["type"] == "image/pjpg"))
            && ($_FILES["photo"]["size"] < 100000000))
            {
                move_uploaded_file($_FILES["photo"]["tmp_name"], $target.$name);

                if(mysql_query("your query"))
                {
                    //success handling
                }
                else 
                {
                    //failed handling
                }
            }
            else
            {
                //error handling
            }
?>

希望这可能会有所帮助。

【讨论】:

    【解决方案3】:
    <form method="post" action="addMember.php" enctype="multipart/form-data">
        <p>
                  Please Enter the Band Members Name.
                </p>
                <p>
                  Band Member or Affiliates Name:
                </p>
                <input type="text" name="nameMember"/>
                <p>
                  Please Enter the Band Members Position. Example:Drums.
                </p>
                <p>
                  Band Position:
                </p>
                <input type="text" name="bandMember"/>
                <p>
                  Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
                </p>
                <p>
                  Photo:
                </p>
                <input type="hidden" name="size" value="350000">
                <input type="file" name="photo"> 
                <p>
                  Please Enter any other information about the band member here.
                </p>
                <p>
                  Other Member Information:
                </p>
    <textarea rows="10" cols="35" name="aboutMember">
    </textarea>
                <p>
                  Please Enter any other Bands the Member has been in.
                </p>
                <p>
                  Other Bands:
                </p>
                <input type="text" name="otherBands" size=30 />
                <br/>
                <br/>
                <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
              </form>
    

    另存为 addMember.php

    <?php
    
    //This is the directory where images will be saved
    $target = "your directory";
    $target = $target . basename( $_FILES['photo']['name']);
    
    //This gets all the other information from the form
    $name=$_POST['nameMember'];
    $bandMember=$_POST['bandMember'];
    $pic=($_FILES['photo']['name']);
    $about=$_POST['aboutMember'];
    $bands=$_POST['otherBands'];
    
    
    // Connects to your Database
    mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
    mysql_select_db("dbName") or die(mysql_error()) ;
    
    //Writes the information to the database
    mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
    VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
    
    //Writes the photo to the server
    if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
    {
    
    //Tells you if its all ok
    echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
    }
    else {
    
    //Gives and error if its not
    echo "Sorry, there was a problem uploading your file.";
    }
    ?>
    

    在上面的代码中有一个小错误,我修复了那个错误。

    【讨论】:

      【解决方案4】:

      添加以下内容可避免文件名中的引号问题,例如

      "freddy's pic.jpg"
      

      这在某些操作系统上是可以接受的。

      之前:

      $pic=($_FILES['photo']['name']);
      

      之后:

      $pic=(mysql_real_escape_string($_FILES['photo']['name']));
      

      【讨论】:

        【解决方案5】:

        你的部分:

        $result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name
        
        Error: " . mysql_error());
        
        mysql_select_db("project") or die("Could not select database");
        mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
        if($result) { echo "Image name saved into database
        
        ";
        

        没有多大意义,您的连接不应命名为 $result 但这是命名问题而不是编码问题。

        什么是编码问题是 if($result),如果您说无论插入查询失败还是成功都可以连接到数据库,那么您将输出“图像保存到数据库中”。

        尝试添加做

        $realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
        

        并将 if($result) 更改为 $realresult

        我怀疑你的查询失败了,也许你有额外的列或什么?

        尝试复制/粘贴您的查询,替换“.$_FILES['filep']['name']。”在你的查询浏览器中测试并运行它,看看它是否进入。

        【讨论】:

          【解决方案6】:

          如果您想在表单中输入更多数据,您只需通过 $_POST 访问提交的数据。

          如果你有

          <input type="text" name="firstname" />
          

          你用

          访问它
          $firstname = $_POST["firstname"];
          

          然后您可以将查询行更新为读取

          mysql_query("INSERT INTO dbProfiles (photo,firstname)
                       VALUES('{$filename}','{$firstname}')");
          

          注意:始终过滤和清理您的数据。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-08-28
            • 2017-08-11
            • 1970-01-01
            • 1970-01-01
            • 2018-07-20
            • 2017-06-18
            • 2014-05-09
            相关资源
            最近更新 更多