php server and sql image upload
Ok,
I have built an insert image page (uploader.php) on the back of a previous post with regards to setting up a php image uploader, but am having a few issues......
The code is:
<?php
$target = "images/test/";
$target = $target . basename( $_FILES['photo']['name']);
$title=$_POST['title'];
$desc=$_POST['desc'];
$pic=($_FILES['photo']['name']);
mysql_connect("dbhost", "dbuser", "dbpass") or die(mysql_error()) ;
mysql_select_db("dbname") or die(mysql_error()) ;
mysql_query("INSERT INTO `test` VALUES ('$title', '$desc', '$pic')") ;
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Title: <input type="text" name="title"><br>
Description: <input type="text" name = "desc"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Add">
</form>
So the first issue is that the开发者_如何学Go information is not being entered into the database - the table has 4 fields - id(int), title(varchar), desc(varchar) and photo(varchar). Is it because the id field is not being specified?? This is simply the auto incremented primary key for the table.
The second issue is that the image that is being loaded contains spaces in it - for example, when uploading "test image.jpg"
- I would like to incorporate a str_replace()
to create "testimage.jpg"
. Do you know where I would insert this into the code?
Thanks again for any help,
JD
If you don't explicitly list columns in your insert statement, you must include all of them in the VALUES ()
, so yes you would need to include the id
Better though, would be to list the columns:
mysql_query("INSERT INTO `test` (title, `desc`, photo) VALUES ('$title', '$desc', '$pic')") ;
Note that desc
is backquoted above. It is a MySQL reserved keyword and is a syntax error there unless quoted.
Also, please escape your values against SQL injection!
$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);
$pic = (mysql_real_escape_string($_FILES['photo']['name']));
// And your space replacement
$pic = str_replace(" ","", $pic);
// Now that it's cleaned up, you can insert.
mysql_query("INSERT INTO `test` (title, `desc`, photo) VALUES ('$title', '$desc', '$pic')") ;
精彩评论