php 如何在使用PHP将图像上传到服务器时将文件名存储在数据库中以及其他信息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/450876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store file name in database, with other info while uploading image to server using PHP?
提问by
Hi I have read many forums and websites that tell you how to upload an image to a server and I have managed to get this working, I can upload a file to a my server but storing the file name does work on the following example I found and I also need to create a form that allows more data to be entered to the database. I am stuck with this as a have done much PHP before. I have come to the end of trying different websites tutorials with no much success could anyone please help me! I need it done for a project I'm doing.
嗨,我已经阅读了许多论坛和网站,这些论坛和网站告诉您如何将图像上传到服务器,并且我已经设法使其正常工作,我可以将文件上传到我的服务器,但存储文件名确实适用于我发现的以下示例我还需要创建一个表单,允许将更多数据输入到数据库中。我坚持这一点,因为以前做过很多 PHP。我已经尝试了不同的网站教程,但没有取得多大成功,任何人都可以帮助我!我需要为我正在做的项目完成它。
I am basically trying to make a CMS that allows users to upload a photo of a band member and have information stored about them so that it can be displayed on a webpage for the public to view.
我基本上是在尝试制作一个 CMS,它允许用户上传乐队成员的照片并存储有关他们的信息,以便可以将其显示在网页上供公众查看。
My Table looks like this:
我的表看起来像这样:
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
The form I want will look like this:
我想要的表格如下所示:
<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>
The Example that uploads an Image to the server and only, that is this:
仅将图像上传到服务器的示例,即:
<?
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
"; }
}
?>
And the Examples form I have to use is this:
我必须使用的示例表单是这样的:
<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: Images file is open for writing to.
PS:图像文件已打开可写入。
回答by Cool Hand Luke
Here is the answerfor those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database.Please let me know if it helped.
这是为那些看起来像我在整个网络上试图找出如何完成此任务的人的答案。使用存储在 mysql 数据库中的文件名和数据库中所需的其他表单数据将照片上传到服务器。如果有帮助,请告诉我。
Firstly the form you need:
首先你需要的表格:
<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>
Then this code processes you data from the 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.";
}
?>
Code edited from www.about.com
代码编辑自www.about.com
回答by Harmando Taufik Gemilang
You have an ID for each photo so my suggestion is you rename the photo. For example you rename it by the date
每张照片都有一个 ID,所以我的建议是重命名照片。例如,您按日期重命名它
<?php
$date = getdate();
$name .= $date[hours];
$name .= $date[minutes];
$name .= $date[seconds];
$name .= $date[year];
$name .= $date[mon];
$name .= $date[mday];
?>
note: don't forget the file extension of your file or you can generate random string for the photo, but I would not recommend that. I would also recommend you to check the file extension before you upload it to your directory.
注意:不要忘记文件的文件扩展名,或者您可以为照片生成随机字符串,但我不建议这样做。我还建议您在将文件上传到目录之前检查文件扩展名。
<?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
}
?>
Hope this might help.
希望这可能会有所帮助。
回答by arjun
<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>
save it as addMember.php
将其另存为 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.";
}
?>
in the above code one little bug ,i fixed that bug.
在上面的代码中一个小错误,我修复了那个错误。
回答by pog
Adding the following avoids problems with quotes in file names, e.g.
添加以下内容可避免文件名中的引号问题,例如
"freddy's pic.jpg"
which are acceptable on some operating systems.
这在某些操作系统上是可以接受的。
Before:
前:
$pic=($_FILES['photo']['name']);
After:
后:
$pic=(mysql_real_escape_string($_FILES['photo']['name']));
回答by Sampson
If you want to input more data into the form, you simply access the submitted data through $_POST.
如果您想在表单中输入更多数据,只需通过 $_POST 访问提交的数据。
If you have
如果你有
<input type="text" name="firstname" />
you access it with
你访问它
$firstname = $_POST["firstname"];
You could then update your query line to read
然后您可以更新您的查询行以阅读
mysql_query("INSERT INTO dbProfiles (photo,firstname)
VALUES('{$filename}','{$firstname}')");
Note:Always filter and sanitize your data.
注意:始终过滤和清理您的数据。
回答by savageguy
Your part:
你的部分:
$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
";
Doesn't make much sense, your connection shouldn't be named $result but that is a naming issue not a coding one.
没有多大意义,您的连接不应命名为 $result ,但这是一个命名问题而不是编码问题。
What is a coding issue is if($result), your saying if you can connect to the database regardless of the insert query failing or succeeding you will output "Image saved into database".
什么是编码问题是 if($result),您说如果无论插入查询失败还是成功都可以连接到数据库,您将输出“图像已保存到数据库中”。
Try adding do
尝试添加做
$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
and change the if($result) to $realresult
并将 if($result) 更改为 $realresult
I suspect your query is failing, perhaps you have additional columns or something?
我怀疑您的查询失败了,也许您还有其他列或其他内容?
Try copy/pasting your query, replacing the ".$_FILES['filep']['name']." with test and running it in your query browser and see if it goes in.
尝试复制/粘贴您的查询,替换“.$_FILES['filep']['name']”。测试并在您的查询浏览器中运行它,看看它是否进入。

