i have multiple image upload options in the form and they are working fine and update file name in the mysql database columns?
when i uploads image1 then image move on to the server and also it is showing next to html table columns now problem is that when i upload image with file option2 after form submit then image1 which is on the next to the image1 file option will be disappeared and in the mysql database image1 columns will be blank?
Multiple Images Uploading Functions
$id=$_REQUEST['id'];
if(isset($_POST['submit']))
{
if (!empty($_FILES['image']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 25;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image', $file_name, $file_path))
$demo_image = $image->img_path;
}
if (!empty($_FILES['image1']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image1']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 35;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image1', $file_name, $file_path))
$demo_image2 = $image->img_path;
}
if (!empty($_FILES['image2']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image2']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 35;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image2', $file_name, $file_path))
$demo_image3 = $image->img_path;
}
Update Query
UPDATE products SET
image='$demo_image',addimage1='$demo_image2',addimage2='$demo_image3'
WHERE id='$id'
}
Select Images Query
$query1=mysql_query("select images,addimages1,addimages2 from products
where id='$id' ")or die("query");
$row2=mysql_fetch_array($query1);
<form method="post" enctype="multipart/form-data">
Image Upload Option1
<input type="file" name="image" id="image" />
<img src="<?php echo $image['image'] ?>" width="150" height="150" />
Image Upload Option2
<input type="file" name="image1" id="image1"/>
<img src="<?php echo $image['addimage1'] ?>" width="150" height="150" />
Image Upload Option3
<input type="file" name="image2" id="image2"/>
<img src="<?php echo $image['addimage2'] ?>" width="150" height="150" />
<input type="submit" class="bg" name="submit" />
</form>
The problem lays here:
UPDATE products SET
image='$demo_image',addimage1='$demo_image2',addimage2='$demo_image3'
WHERE id='$id'
}
From what I understood you first submit the form where you upload the first image and then you submit the form again where you upload the second image. The reason of this is that during your second upload the variable $demo_image will be blank because you are not sending any value of the input "image" during the resubmit. See here:
$demo_image = $image->img_path;
$image->img_path is blank, therefore $demo_image will be blank (or NULL? - not sure) as well.
There are many solutions of this problem. You can retrieve data from you db to the form and then resubmit, or test if your variables are blank (or NULL?) and then having different UPDATE commands for different variations, or retrieving data from MySQL just before you run UPDATE and many more.
I'd pick retrieving "old" data from MySQL and then just test if their NULL. If they are not NULL in MySQL, you will just resubmit the same data to your db. Like this:
if ($demo_image_from_db!=NULL) $demo_image = $demo_image_from_db;
It is possible that there is also a MySQL native function for updating only when NULL - I've heard of COALESCE but I don't exactly know how to use it - that would be definitely the simplest way to do it.
Related
(I wanted to upload a new image with the same name as previous.
All code is working well...
but when i try to fetch image it show the previous image)
Any Solution????
Mysql Table
My Code
<?php
include "nav.php";
$id = $_GET['id'];
$id = base64_decode($id);
$q = "select * from slider where id =".$id;
include "js.php";
include "db.php";
$r = mysqli_query($con,$q);
$row = mysqli_fetch_assoc($r);
?>
<div style = "width:70%;margin-left:13%;">
<form method = "post" enctype="multipart/form-data">
<br>
<center>
<input type = "text" value="<?php echo $row["text"];?>" name = "title" placeholder="Title" style = "width:100%;" required>
<br>
<br>
<input type="file" name = "m" class="form-control-file" accept="image/x-png,image/gif,image/jpeg" id="exampleFormControlFile1" required>
<input class = "btn btn-primary" type = "submit" name = "submit" value="Submit">
</center>
</form>
</div>
<?php
if(isset($_POST["submit"])){
$t =$_POST['title'];
$allow = array('jpg');
$temp =explode(".",$_FILES['m']['name']);
$extension= end($temp);
$newfilename=$row['id'] .".".$extension;
if($extension=="jpg")
{
$upload_file=$newfilename;
move_uploaded_file($_FILES['m']['tmp_name'] , "slider/".$upload_file);
}
else
{
echo "<script>alert('Image should be in jpg');</script>";
exit();
}
$q = "update slider set text= '".$t."' where id= ".$row['id'];
$r = mysqli_query($con,$q);
header('location:slider.php');
exit();
}
?>
'''
Here how can i use unlink funtion????
or can any one me the code to delete the old image and create and upload a new image with the same name
if you need to update the image in ftp but with the same name in database, first fetch the data from the database for that row and store the value of the image in a variable like this :
// write your sql query here
$upload_file=$old_file_name; // value should be fetch from database.
then unlink the image from the ftp using:
unlink('/path/imagename.png'); // set your path and change the name and extension
once you unlink the image upload the new image and remove while uploading it. so it can remove existing file from ftp and upload new image with old name.
here is the solution .....
(It will delet the old pic and upload the new one in folder....)
<?php
//delet the previous img
unlink("slider/" . $oldimage);
// If upload button is clicked ...
if (isset($_POST['submit'])) {
// Get image name
$title=$_POST['title'];
$filename = $_FILES['image']['name'];
$filetmpname = $_FILES['image']['tmp_name'];
//folder where images will be uploaded
$folder = 'slider/';
//function for saving the uploaded images in a specific folder
move_uploaded_file($filetmpname, $folder.$filename);
//inserting image details (ie image name) in the database
$sql = "UPDATE slider SET image='$filename',text='$title' where id=$id";
$qry = mysqli_query($con, $sql);
if( $qry) {
echo "</br>image uploaded";
}header('Location:slider.php');
}
?>
got uploading idea from here
https://medium.com/#mauricemuteti2015/how-to-upload-and-insert-image-into-mysql-database-using-php-and-html-32633a06d372
I am having trouble making a image deleter in php i do not know what is wrong
PHP:
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
$image = $_POST['dcheck'];
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
?>
HTML:
<form action="Admin3.php" method="post">
<?php
while($check = mysql_fetch_array($query2)){
echo '<img class="images2" src= "/PhotographyMML/Uploads/resized' . $check['PhotoName'] . $check['PhotoType'] . '" height="100" width ="100" ><input type="checkbox" name="dcheck[]" value="'. $check['PhotoNumber'] .'" />';
}
?>
<input type="submit" value="Delete Image(s)" />
</form>
Your dcheck variable is an array. You will want to create an outer loop around the existing query code you have and foreach through the array, deleting each time.
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
foreach ($_POST['dcheck'] as $image) {
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
}
?>
A small optimization would be to alter the query so it uses WHERE A small optimization would be to alter your delete query so that it uses WHERE PhotoNUmber IN (1, 2 ...).
This would cause your deletion to happen in one query rather than N queries.
What seems to be missing is any code to actually remove the original file you're alluding to. That would require some sort of file deletion function typically utilizing http://php.net/manual/en/function.unlink.php
I have this code code below to upload image in a foder uploads/year/month, if this directory does not exist it will create if exists I only do the upload.
After this code, Im doing a insert into my "news" table with this thumb info and the other table news fields.
And it is working fine, Im inserting without any error, its inserting in my database, and the image file is uploading with sucess in my uploads/year/month folder.
But now in my other file "news-edit.php", to edit my news, and I want to show the thumb file in my label.
Im trying to do this for hours and its not working, somebody there can give me a help understanding what is happening?
My php code to upload image
if(!empty($_FILES['thumb']['tmp_name'])){
$folder = '../uploads/';
$year = date('Y');
$month = date('m');
if(file_exists($folder.$resultReadEdit['thumb']) && !is_dir($folder.$resultReadEdit['thumb']))
{
unlink($folder.$resultReadEdit['thumb']);
}
if(!file_exists($folder.$year)){
mkdir($folder.$year,0755);
}
if(!file_exists($folder.$year.'/'.$month)){
mkdir($folder.$year.'/'.$month,0755);
}
$img = $_FILES['thumb'];
$ext = substr($img['name'],-3);
$f['thumb'] = $year.'/'.$month.'/'.$f['url'].'.'.$ext;
uploadImage($img['tmp_name'], $f['url'].'.'.$ext, '300', $folder.$year.'/'.$month.'/');
}
My php to show the image file:
<label class="line">
<?php
$folder = '../uploads/';
$year = date('Y');
$month = date('m');
echo '<a href="'.$folder.$year.'/'.$month.'/'.$resultReadEdit['thumb'].'" rel="Shadowbox">';
echo '<img src="'.$folder.$year.'/'.$month.'/'.$resultReadEdit['thumb'].'" width="50" />';
echo '</a>';
print_r($resultReadEdit['thumb']);
?>
<input type="file" class="fileinput" name="thumb" size="60" />
</label>
What Im getting:
Look at your generated html source code. Since your print_r($resultReadEdit['thumb']) is returning
2014/04/title-of-my-news.png
you are saving $resultReadEdit['thumb'] as year/month/thumb so your html source code probably is looking like
src="uploads/2014/04/2014/04/title-of-my-news.png"
So try changing
echo '<img src="'.$folder.$year.'/'.$month.'/'.$resultReadEdit['thumb'].'" width="50" />';
to
echo '<img src="'.$folder.$resultReadEdit['thumb'].'" width="50" />';
hi guys i am working on a project where i have a student_edit.php file which updates the students
details all my data is updated successfully but there is one problem when i update lets say only two fields and not all then image is blanked and my fields updated successfully.
what i am doing is that i am showing student picture and besides it i have another input fields to browse image to update image. What i want is simple that if i am not updating image instead i update other fields image should be still there and not become blank.
Necessary code snippets is like that:
<?php
$file_name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
if (copy($tmp_name, "images/" . $file_name)) {
$picture = "images/" . $file_name;
}
if (!isset($_POST['picture'])) {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',updated=now() WHERE id='$id'") or die(mysql_error());
}
else {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',`picture`='$picture',updated=now() WHERE id='$id'") or die(mysql_error());
}
?>
and their is picture area where i call pics
<p>
<label for="picture"><strong>Picture:</strong> </label>
<img src="<?php echo $rec['picture'];?>" width="100" height="100"/>
<input name="picture" type="file" value="">
</p>
and their is picture area where i call pics
<p>
<label for="picture"><strong>Picture:</strong> </label>
<img src="<?php echo $rec['picture'];?>" width="100" height="100"/>
<input name="picture" type="file" value="">
</p>
Just a quick guess by looking at your code, you are not escaping the value of $picture when you place it in the database, which could be why the image value in the database is not updating.
Also, don't use if(!isset($_POST['picture'])), but try if (!isset($_FILES['picture']) || (isset($_FILES['picture']) && $_FILES['picture']['name'] == ""). The $_POST super global won't work, because files are sent via the $_FILES super global.
Putting it all together:
$file_name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
if (!isset($_FILES['picture']) || (isset($_FILES['picture']) && $_FILES['picture']['name'] == "")) {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',`picture`='$picture',updated=now() WHERE id='$id'") or die(mysql_error());
} else {
copy($tmp_name, "images/" . $file_name)
$picture = mysql_real_escape_string("images/".$file_name);
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',updated=now() WHERE id='$id'") or die(mysql_error());
}
Also, I REALLY recommend that you use the MySQLi extension: http://php.net/manual/en/book.mysqli.php
The above code is totally untested, but should work.
I am hoping to offer users a user submitted image gallery. I have written a upload script which saves the file above the www root. I know I can serve the file by specifying the page header and then using readfile, however I am planning to throw the images within a table to be displayed with other information and dont think the header/readfile is the best solution. I am thinking maybe symlinks but I am not sure.
What is the best method to achieve this?
You'll need a script like getimage.php which sends the image headers and echo's out its contents. Then in your HTML, you just utilize it as the <img src=''> in your HTML. The only purpose of getimage.php is to retrieve and output the image. It remains separate from whatever PHP you use to generate the HTML sent to the browser.
Additionally, you can check if the user has a valid session and permission to view the image in getimage.php and if not, send a some kind of access-denied image instead.
The contents of getimage.php are small and simple:
// Check user permissions if necessary...
// Retrieve your image from $_GET['imgId'] however appropriate to your file structure
// Whatever is necessary to determine the image file path from the imgId parameter.
// Output the image.
$img = file_get_contents("/path/to/image.jpg");
header("Content-type: image/jpeg");
echo($img);
exit();
In your HTML:
<!-- as many as you need -->
<img src='getimage.php?imgId=12345' />
<img src='getimage.php?imgId=23456' />
<img src='getimage.php?imgId=34567' />
It then becomes the browser's job to call getimage.php?imgId=12345 as the path to the image. The browser has no idea it is calling a PHP script, rather than an image in a web accessible directory.
If the script is running on a Unix server, you might try to create a symlink in your web root that links to the directory outside of your web root.
ln -s /webroot/pictures /outside-of-webroot/uploads
If you're using an Apache server you could also have a look at mod_alias.
I've heard that there are a few issues when using mod_alias and configuring it through .htaccess. Unfortunately I don't have any experience with mod_alias whatsoever.
Something that always has worked well for me is to have users upload their images directly into my mysql db. The PHP will encode into base64 and store into a blob. Then you do something similar to what michael said to retrieve and display the image. I've included some code from a project I was working on in 2008. I wouldn't copy it exactly if it's a method you're interested in using since it's old code.
This is the PHP to upload and store into a DB. Obviously replace your info and connect to your own DB.
<?php
include("auth.php");
// uploadimg.php
// By Tyler Biscoe
// 09 Mar 2008
// Test file for image uploads
include("connect.php");
include("include/header.php");
$max_file_size = 786432;
$max_kb = $max_file_size/1024;
if($_POST["imgsubmit"])
{
if($_FILES["file"]["size"] > $max_file_size)
{
$error = "Error: File size must be under ". $max_kb . " kb.";
}
if (!($_FILES["file"]["type"] == "image/gif") && !($_FILES["file"]["type"] == "image/jpeg") && !($_FILES["file"]["type"] == "image/pjpeg"))
{
$error .= "Error: Invalid file type. Use gif or jpg files only.";
}
if(!$error)
{
echo "<div id='alertBox'> Image has been successfully uploaded! </div>";
$handle = fopen($_FILES["file"]["tmp_name"],'r');
$file_content = fread($handle,$_FILES["file"]["size"]);
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$id = $_POST["userid"];
echo $_FILES["file"]["tmp_name"];
$default_exist_sql = "SELECT * FROM members WHERE id='".$id."'";
$default_result = mysql_query($default_exist_sql);
$results = mysql_fetch_array($default_result);
if(!$results["default_image"])
{
$insert_sql = "UPDATE members SET default_image = '$encoded' WHERE id='". $id ."'";
mysql_query($insert_sql);
}
$sql = "INSERT INTO images (userid, sixfourdata) VALUES ('$id','$encoded')";
mysql_query($sql);
}
else
{
echo "<div id='alertBox'>". $error . "</div>";
}
}
?>
<br />
<font class="heading"> Upload images </font>
<br /><br />
<form enctype = "multipart/form-data" action = "<?php $_SERVER['PHP_SELF']; ?>" method = "post" name = "uploadImage">
<input type = "hidden" name="userid" value = "<?php echo $_GET["userid"]; ?>" >
<input id="stextBox" type="file" name="file" size="35"><br />
<input type="submit" name="imgsubmit" value="Upload">
</form>
<?php include("include/footer.php"); ?>
This next one displays the file:
<?php
// image.php
// By Tyler Biscoe
// 09 Mar 2008
// File used to display pictures
include("connect.php");
$imgid = $_GET["id"];
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $imgid . "");
$image = mysql_fetch_array($result);
echo base64_decode($image["sixfourdata"]);
echo $image["sixfourdata"];
?>
Then:
<img src="image.php?id=your_img_id">