Issue with updating image info on MYSQL database using PHP - php

I'm having problem with my code. I can't update my image.
Here is my full code:
index.php
//this link will post my data to next page
update
updatepage.php
//this page will get all data that want to update...
<?php
include("config.php");
$name=$_GET['code'];
$sql1 = "select * from imagename where name='$name'";
$result = mysql_query($sql1) or die(mysql_error());
$row=mysql_fetch_array($result);?>
<form name="form1" method="post" action="processupdatepage.php" class="formposition" enctype="multipart/form-data" >
<table>
<tr><td>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" /></td></tr>
<tr><td width="98">Image</td><td width="288">
//This is where I have problem, I can't get my image value but other data value work very well.....
<input type="file" name="image" value="<?php echo $row['image'];?>" /></td></tr><br/>
<tr><td>nane</td><td><input type="text" name="name" value="<?php echo $row['name']; ?>"/></td></tr><br/>
<tr><td></td> <td colspan="2">
<input type="submit" name="submit" value="Save" /> </td></tr>
</table>
</form>
OK. Now this my process file:
processupdatepage.php
<?php
include("config.php");
$id=$_POST['id'];
$image=$_FILES['image']['name'];
$name=$_POST['name'];
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
$query = "UPDATE imagename SET name='$name', image='$image' WHERE id='$id'";
$bb = mysql_query($query) or die(mysql_error());
if($bb)
{
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$sql001="UPDATE imagename SET image='$image' WHERE image='$image'";
mysql_query($sql001);
} else { }
header("Location:index.php");
}
else
{
echo "Could not be updated";
}
?>
I can update BUT must select image. If I'm not selecting an image, my image field in database will be empty BUT other data updates are OK...

The value of an <input type="file"> cannot be programatically changed. Only by triggering its default behaviour that pops up the select file dialogue.
What I see from you example code is that you want to associate the value to the file form control element straight as it was retrieved from the database. So why saving the same back. Still, if you want to do this, you can use a hidden element with the value, that will be saved. But if you don't want the user to change it, just don't render it into the form and leave it out from your update query so it will remain unchanged.
Also, you could add some logic when you process the post and leave the field 'image' out of your update query if no file was selected.

I think the problem is here:
<input type="file" name="image" value="<?php echo $row['image'];?>" />
You can upload the image by clicking the browse button. so what do you trying to do like that?
If you want to show the image already uploaded you can use :
$img_path = 'get image path from database entry';
<img src= "<?php echo $img_path; ?>"/>

Here is full code to upload an Image, this is tested and works but you need to have a directory called 'upload' (this code does not create the folder).
It is advisable to only store image path on database.
<?php
if(isset($_POST['submit'])){
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
// HERE YOU CAN WRITE YOU INSERT INTO MYSQL CODE
//SOMETHING LIKE THIS:
$path = 'assets/article_images/'.$article_id.'/'.$_FILES["image_file"]["name"];
$statement1 = "INSERT INTO image_article (article_id, image_path) values ('$article_id', '$path') ";
$query_result = mysql_query($statement1) or die($statement1."mysql error<br/><br/>".mysql_error());
if($query_result==1){
echo 'Image uploaded';
}
}
}
}
else
{
echo "Invalid file";
}
}
?>
<html>
<body>
<form action="index.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

Related

Does an update have to be different to an insert when uploading a file?

I'm having a problem with the update section of a CRUD I'm making. The create works fine, and I'm using very similar code for the update but there's something going wrong and it seems to be a problem with the file upload.
I have a page that displays all the rows from the database. There's a link next to each row that says edit and when that's clicked on, it goes to a page that displays the row from the Db in a form. The information can then be changed and there's a submit button that when clicked makes the action of the form run, which is a php file that has this:
<?php
include ('includes/DbCon.php');
if (isset($_POST['ud_id']))$id = $_POST['ud_id'];
$query = "SELECT * FROM news WHERE id = '$id'";
$result = $mysqli->query ($query);
if(mysqli_num_rows($result)>=1)
{
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
$headline = $row['headline'];
$body = $row['body'];
$image = $row['image'];
}
else{
$mysqli->error;
}
//Set directory etc for image upload
$target_dir = "images/photo/";
$target_file = $target_dir . basename($_FILES["ud_image"]["name"]);
if (move_uploaded_file($_FILES["ud_image"]["tmp_name"], $target_file)or die($mysqli->error))
{
echo '<script type="text/javascript">';
echo 'alert("News Items Saved")';
echo '</script>';
} else {
echo "Sorry, there was an error with your file.";
}
There's more to it but it doesn't get past this, so I need help figuring out what's wrong with it. I've used var_dump and also printed the variables to see what's getting passed and everything is fine until it get's to the $target_file. When I print that variable I get 'image/photo' but I suspect it should be the full file name as well as the target path.
It's set the same way as the insert code, so I don't know what's wrong with it.
As requested, here's the form:
<form action="update.php" method="post" class="newNews">
<input type="hidden" name="ud_id" value="<?=$id;?>">
<label for="title">Title</label><br />
<input type="text" name="ud_headline" value="<?=$headline;?>"/>
<label for="text">Body</label><br />
<textarea name="ud_body" rows="5" cols="21" value="" class="editBody"><?=$body;?></textarea>
<p>Current Photo</p>
<img src="images/photo/<?=$image?>" alt=" " width="auto" height="auto"><br />
<input type="file" name="ud_image" class="newsImage" ><br />
<input type="submit" name="submit" value="Update news item" class='addNew' />
</form>
It appears to be a problem with your move_uploaded_file() function. From the online manual:
http://php.net/manual/en/function.move-uploaded-file.php
Try this code:
<?php
...
if ($_FILES["ud_image"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["ud_image"]["tmp_name"];
$name = $_FILES["ud_image"]["name"];
if (move_uploaded_file($tmp_name, "$target_dir$name"))
{
echo '<script type="text/javascript">';
echo 'alert("News Items Saved")';
echo '</script>';
}
else
{
echo "Sorry, there was an error with your file.";
}
}
else
{
echo "Sorry, there was an error with your file.";
}

Multiple Upload using CTRL Key PHP

would you help for my code , i need to do the multiple upload but i cant so will you help me please. i need so bad.
here's my code
i made multiple upload the form but it is not working. the output is "error array"
//HTML
<html>
<head>
<form name="Image" enctype="multipart/form-data" action="upload.php" method="POST">
<h1><font face="tahoma"> UPLOAD FILES</h1>
<label for="file">Filename:</label>
<input type="file" name="Photo[]" accept="image/*" multiple="multiple"/><br/><br/>
<input type="hidden" id="pageName" name="pageName">
<script type="text/javascript">
//get page name from parent
var value = window.opener.pageName
document.getElementById("pageName").value = value;
</script>
<INPUT type="submit" class="button" name="Submit" value=" Upload ">
<INPUT type="reset" class="button" value="Cancel"><br/><br/>
</form>
</head>
</html>
//PHP this is were upload is do.
<?php
include('global.php');
?>
<?
$uploadDir = 'directory/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'][0];
$fileName1 = $_FILES['Photo']['name'][1];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName . $fileName1;
//upload error
if ($_FILES["Photo"]["error"] > 0)
{
echo "Error: " . $_FILES["Photo"]["error"] . "<br />";
}
//photo already exixts
else
//insert image into DB
{
move_uploaded_file($tmpName, $filePath);
$filePath = addslashes($filePath);
$filePath = stripslashes($filePath);
$filePath = mysql_real_escape_string($filePath);
$query = "INSERT INTO images (image , category ) VALUES ('$filePath', '$pageName')";
mysql_query($query) or die('Error, query failed');
echo" Upload Successful. <br/> <br/>";
echo "Stored in: " . "directory/" . $_FILES["Photo"]["name"];
?>
<br/><br/>
<img width="300" height="400" src="directory /<?=$_FILES["Photo"]["name"]?>"><br/>
<?
}
}
?>
Error: Array is telling you that the error being returned is actually an Array object, not a string. If you want to see the actual error message, you need to view the full contents of the array. Something like print_r($_FILES["Photo"]["error"]); or looping through the array like so
foreach($_FILES["Photo"]["error"] as $err) {
echo "error: " . $err . "<br>";
}
Or you can just print the first error returned just as you have returned the first file in your name array echo $_FILES["Photo"]["error"][0];

PHP File upload, if left blank

I having a bit of an issue with my file upload, it works fine and everything, but I goto update my data and I want to change everything except for the image and hit submit, I get the Invalid Image message, I am not updating the images so there is no file in the file input text box, is there a way to bypass this?
if (($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/pjpeg")){
if ($_FILES["image"]["error"] > 0){
echo $_FILES["image"]["error"];
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"../upload/CV_1_" . date("Ymd") . $_FILES["image"]["name"]);
$class->update($id, $text, $image);
echo "<div style='padding-left:50px'><strong>Updated!</strong></div>";
}
}else{
echo "<div style='padding-left:50px'><strong>Invalid Image!</strong></div>";
}
What the code above does is take the file, see if its an image and if there are any errors, show them, then it moves the file into the proper folder and updates my database.
Here is the form...
<form action="CV.php?action=updatesubmit" method="post" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $array['id']; ?>" name="id" />
<p>
<label for="text" style="vertical-align:top;">Text</label>
<textarea name="text" id="text" cols="70" rows="20"><?php echo $array['text']; ?></textarea>
</p>
<p>
<label for="image">Image</label>
<input type="file" name="image" id="image" value="<?php echo $array['image']; ?>" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Update" />
</p>
</form>
I hope I made sense, I have a habit of tying something out, it sounds good to me but other people wont know what I am talking about.
Played with my code and this was suggested but its not working, I'm probably doing something wrong.
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
if (($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/pjpeg")){
if ($_FILES["image"]["error"] > 0){
echo $_FILES["image"]["error"];
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"../upload/CV_1_" . date("Ymd") . $_FILES["image"]["name"]);
}
$class->update($id, $text, $image);
echo "<div style='padding-left:50px'><strong>Updated!</strong></div>";
}
}else{
echo "<div style='padding-left:50px'><strong>Invalid Image!</strong></div>";
}
You need to check for an actual upload before you do ANYTHING ELSE with the upload data:
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
... got an upload ...
}
Just put if(isset($_FILES['image'])) around the whole block. If no image is uploaded, the file entry won't be there.
It will submit if and only if image is uploaded.
<?php
if ($_FILES["image"]["tmp_name"] && $_FILES["file"]["error"] < 0){
if (($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/pjpeg")){
if ($_FILES["image"]["error"] > 0){
echo $_FILES["image"]["error"];
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"../upload/CV_1_" . date("Ymd") . $_FILES["image"]["name"]);
$class->update($id, $text, $image);
echo "<div style='padding-left:50px'><strong>Updated!</strong></div>";
}
}else{
echo "<div style='padding-left:50px'><strong>Invalid Image!</strong></div>";
}
}
?>

php .flv file uploading issue

well I can upload image, mp3, mp4, .doc file etc with the following form. But it's doesn't upload .flv file. Anyone can tell me what is the problem in my code or how can i upload .flv..
<?php
$mysql_connect = mysql_connect("localhost", "root" );
mysql_select_db("vedio");
ini_set('upload_max_filesize','1000M');
if(isset($_POST['action']) == "upload")
{
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$size = $_FILES['file']['size'];
$type = $_FILES['file']['type'];
$name = str_replace(" ", "", $name);
$sql = mysql_query("INSERT INTO content VALUES('',
'$name', '$tmp_name', '$size' )");
if($sql)
{
echo "successfully uploaded";
}
else
{
echo "Something is wrong to upload";
}
$upload = "vedio/";
move_uploaded_file($_FILES['file']['tmp_name'], $upload . $name);
echo "<br/>";
echo $name;
echo "<br/>";
echo $tmp_name;
echo "<br/>";
echo $size;
echo "<br/>";
echo $type;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000000000" />
<table width="400" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="submit" value="upload" name="action" /></td>
</tr>
</table>
</form>
Many Thanks.
Shibbir
My guess is your flv is probably just too big..
upload_max_filesize alone is not enough to set, you also need to set post_max_size otherwise your POST request will be empty and your upload will fail (it'll essentially look like a non-post request).
This line doesn't make sense
if(isset($_POST['action']) == "upload")
you are calling isset() which is going to return true or false depending upon if that variable is given a value and then you compare that true or false with the string "upload" which obviously would never be equal. You either need to check if the variable is set or check if the value is equal to "upload".
if(isset($_POST['action']) && $_POST['action'] == "upload")
Should also check for file upload errors. Something like:
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else {
echo "No file upload errors";
}

PHP File upload form not working

I've used this code in another site I've made and it works absolutely fine so I'm really confused as to why this isn't working properly. The only things I have changed are the directories for the file to be moved to, but the files never get uploaded. I've triple checked everything and it all seems fine. The code all executes without errors and all of the info gets entered into the database correctly, the only problem is the file not uploading. I'm going mad trying to get this to work! please help!
HTML FORM:
<p>
<h2>Add News</h2><br />
REQUIRED *<br /><br />
<form enctype="multipart/form-data" action='addnews2.php' method='post' onsubmit="chose.value = uploadForm()" name="newsform">
<p>Headline: *
<br>
<input name="title" type="text" size="75">
<br />
<br/>
News: *<br>
<textarea name="text" cols="75" rows="10" width="200"></textarea><br /><br />
Image File:
<br>
<input type="file" name="filetoupload" id="filetoupload"><br/><br />
<input type="submit" name="choose" value="Submit" />
</p>
</form>
</p>
Processing Page:
$date=date("l F d, Y");
$title=stripslashes($_POST['title']);
$text=stripslashes($_POST['text']);
if (($_FILES["filetoupload"]["type"] == "image/gif")
|| ($_FILES["filetoupload"]["type"] == "image/jpeg")
|| ($_FILES["filetoupload"]["type"] == "image/pjpeg")
|| ($_FILES["filetoupload"]["type"] == "image/png")
|| ($_FILES["filetoupload"]["type"] == "image/jpg"))
{
if ($_FILES["filetoupload"]["error"] > 0)
{
echo "Return Code: " . $_FILES["filetoupload"]["error"] . "<br />";
}
else
{
if (file_exists("images/news/" . $_FILES["filetoupload"]["name"]))
{
echo $_FILES["filetoupload"]["name"] . " already exists. ";
}
move_uploaded_file($_FILES["filetoupload"]["tmp_name"],
"images/news/" . $_FILES["filetoupload"]["name"]);
}
}
$image = "images/news/".$_FILES['filetoupload']['name'];
if($title==""||$text==""){
die("You need to fill in all details");
}
connect_to_db();
$query="insert into news (date, title, text, image) values ('".$date."','".mysql_real_escape_string($title)."','".mysql_real_escape_string($text)."','".$image."')";
$result=mysql_query($query);
if(mysql_affected_rows()==1){
header("Location:index.php?page=Admin&news=added");
}
else{
die("there was a problem");
}
mysql_close();
Looks like you are missing an else statement possibly, the code formatting is off and causes confusion:
if (file_exists("images/news/" . $_FILES["filetoupload"]["name"]))
{
echo $_FILES["filetoupload"]["name"] . " already exists. ";
}else {
move_uploaded_file($_FILES["filetoupload"]["tmp_name"],
"images/news/" . $_FILES["filetoupload"]["name"]);
}
Give that a shot. If not that, check your permissions etc. And make sure that the file isn't being uploaded, just not in the spot you expected it to be.
Just a bit of information, I would do the $title and $text check before you do the image check. As you probably do not want to upload the image to the site if both of those are null. You should also escape the file name in the image path prior to inserting:
$image = "images/news/".mysql_real_escape_string($_FILES['filetoupload']['name']);
As that could also be prone to injection.

Categories