I was wondering if some one can give me an example on how to delete an image using PHP & MySQL?
The image is stored in a folder name thumbs and another named images and the image name is stored in a mysql database.
Delete the file:
unlink("thumbs/imagename");
unlink("images/imagename");
Remove from database
$sql="DELETE FROM tablename WHERE name='imagename'"
$result=mysql_query($sql);
Assuming name is the the name of the field in the database holding the image name, and imagename is the image's name.
All together in code:
$imgName='sample.jpg';
$dbFieldName='name';
$dbTableName='imageTable';
unlink("thumbs/$imgName");
unlink("images/$imgName");
$sql="DELETE FROM $dbTableName WHERE $dbFieldName='$imgName'";
mysql_query($sql);
try this code :
$img_dir = 'image_directory_name/';
$img_thmb = 'thumbnail_directory_name/';// if you had thumbnails
$image_name = $row['image_name'];//assume that this is the image_name field from your database
//unlink function return bool so you can use it as conditon
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
//assume that variable $image_id is queried from the database where your image record your about to delete is...
$sql = "DELETE FROM table WHERE image_id = '".$image_id."'";
$qry = mysql_query($sql);
}else{
echo 'ERROR: unable to delete image file!';
}
Are you looking for actual code or just the idea behind it?
You'll need to query the db to find out the name of the file being deleted and then simply use unlink to delete the file in question.
so here's some quick code to get you started
<?php
$thumb_dir = "path/to/thumbs/";
$img_dir = "path/to/images/";
/* query your db to get the desired image
I'm guessing you're using a form to delete the image?
if so use something like $image = $_POST['your_variable'] to get the image
and query your db */
// once you confirm that the file exists in the db check to see if the image
// is actually on the server
if(file_exists($thumb_dir . $image . '.jpg')){
if (unlink($thumb_dir . $image . '.jpg') && unlink($img_dir . $image . '.jpg'))
//it's better to use the ID rather than the name of the file to delete it from db
mysql_query("DELETE FROM table WHERE name='".$image."'") or die(mysql_error());
}
?>
if(!empty($_GET['pid']) && $_GET['act']=="del")
{
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".$_DIR['site']['adminurl']."mservices".$atend."suc".$_DELIM."3".$baratend);
exit();
}
}
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".
Related
this is my code updating data. How is it possible to use old image if no image is selected?
its a profile page when someone updates his profile but don't select the image for update then old image should be remained there..
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
if(isset($name)){
move_uploaded_file($temp_name,$location.$name);
}
else
{
echo $user_img;
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
First, you need to fetch the existing user details from the database and check if the user already has a profile picture.
Next, if the user has uploaded a new image, then you can delete the old profile picture using unlink() function. If the user has not uploaded a new picture, you can retain the old picture.
See the code below.
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
//Fetch user details
$query = "SELECT User_Pic FROM user WHERE Id=" . $update_id;
$result = mysqli_query($con, $query);
$row = false;
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}
if (isset($_FILES['user_img'])) { //User uploaded new image
if ($row) {
unlink($location . $row['User_Pic']); //Delete old pic
}
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
move_uploaded_file($temp_name,$location.$name);
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
} else { //User did not upload image
if ($row) {
echo $location . $row['User_Pic']; //Echo current image path
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username' where Id='$update_id'";
}
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
Please note that the code shown here does not change the filename when storing the files on the server. This will cause problems when two person upload pictures with same filename. You need to implement an appropriate solution for that.
I am a beginner in PHP. I encoded some images in a base64String. All images are successfully decoding in the specified folder. My problem is am only able to record one image/path in the database. Somebody help me to come up with the PHP to insert all images paths in one row in the database.
here is the php code
<?PHP
if(isset($_POST['image']))
{
$image = $_POST['image'];
$identity = $_POST['id'];
$username = $_POST['username'];
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);
$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";
mysqli_query($conn, $sql);
}
else{
echo "uploaded_failed";
}
exit;
}
else{
echo "images_not_in";
exit;
}
?>
You need some sort of loop...all I did in the example below was instead of making a single variable called image I made a array called $imagesArr. And I added a foreach loop on the imagesArr so it will run the code you wrote for each image you input into that array. I also killed the exit at the end as that would stop the loop. That should work
<?PHP
if(isset($_POST['image']))
{
//$image = $_POST['image']; - I commented this out
$imagesArr = array('image1.jpeg','image2.jpeg','image3.jpeg'); //etc. put all of your images here into this array
$identity = $_POST['id'];
$username = $_POST['username'];
foreach ($imagesArr as $key => $image) {
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);
$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";
mysqli_query($conn, $sql);
}
else{
echo "uploaded_failed";
}
}
else{
echo "images_not_in";
}
}
This question already has answers here:
How to retrieve images from MySQL database and display in an html tag
(4 answers)
Closed 1 year ago.
I am trying to display an image coming from the database and I was not able to display the image .but its showing like this user-1.jpg Please see my code can one guide me how to display the image.
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysql_query($sqlimage);
while($rows = mysql_fetch_assoc($imageresult1))
{
$image = $rows['image'];
print $image;
}
Displaying an image from MySql Db.
$db = mysqli_connect("localhost","root","","DbName");
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';
For example if you use this code , you can load image from db (mysql) and display it in php5 ;)
<?php
$con =mysql_connect("localhost", "root" , "");
$sdb= mysql_select_db("my_database",$con);
$sql = "SELECT * FROM `news` WHERE 1";
$mq = mysql_query($sql) or die ("not working query");
$row = mysql_fetch_array($mq) or die("line 44 not working");
$s=$row['photo'];
echo $row['photo'];
echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
?>
<?php
$connection =mysql_connect("localhost", "root" , "");
$sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
$imageresult1 = mysql_query($sqlimage,$connection);
while($rows = mysql_fetch_assoc($imageresult1))
{
echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
}
?>
You need to do this to display image
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysql_query($sqlimage);
while($rows=mysql_fetch_assoc($imageresult1))
{
$image = $rows['image'];
echo "<img src='$image' >";
echo "<br>";
}
You need to use html img tag.
put you $image in img tag of html
try this
echo '<img src="your_path_to_image/'.$image.'" />';
instead of
print $image;
your_path_to_image would be absolute path of your image folder like eg: /home/son/public_html/images/ or as your folder structure on server.
Update 2 :
if your image is resides in the same folder where this page file is exists
you can user this
echo '<img src="'.$image.'" />';
instead of print $image; you should go for print "<img src=<?$image;?>>"
and note that $image should contain the path of your image.
So,
If you are only storing the name of your image in database then instead of that you have to store the full path of your image in the database like /root/user/Documents/image.jpeg.
Simply replace
print $image;
with
echo '<img src=".$image." >';
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysqli_query($link, $sqlimage);
while($rows=mysqli_fetch_assoc($imageresult1))
{
echo "<img src = 'Image/".$row['image'].'" />';
}
<?php
$conn = mysql_connect ("localhost:3306","root","");
$db = mysql_select_db ("database_name", $conn);
if(!$db) {
echo mysql_error();
}
$q = "SELECT image FROM table_name where id=4";
$r = mysql_query ("$q",$conn);
if($r) {
while($row = mysql_fetch_array($r)) {
header ("Content-type: image/jpeg");
echo $row ["image"];
}
}else{
echo mysql_error();
}
?>
sometimes problem may occures because of port number of mysql server is incoreect to avoid it just write port number with host name like this "localhost:3306"
in case if you have installed two mysql servers on same system then write port according to that
in order to display any data from database please make sure following steps
1.proper connection with sql
2.select database
3.write query
4.write correct table name inside the query
5.and last is traverse through data
put this code to your php page.
$sql = "SELECT * FROM userdetail";
$result = mysqli_query("connection ", $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
echo "<img src='images/".$row['image']."'>";
echo "<p>".$row['text']. "</p>";
}
i hope this is work.
This code runs when a user hits a delete button on my form. I am trying to copy a file, $picfile, from "/pics/" to "/pics/deletedrecordpics/" and then delete the orginal. Finally, delete the record from the database. Deleting the record from the databse works, but copying the file and deleting the original does nothing. There are no errors in the error log, so I am really confused as to why this code isn't running as I think it should.
if ($allowdelete==true && $thepassword == $password)
{
//delete record that delete was set to by button
//$sql = ("DELETE FROM $table WHERE id=$id");
$sql = ("select picfile,title,author from $table where id=$delete");
$file=mysql_query($sql);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
if (file_exists("/pics".$picfile)){
copy("/pics/".$picfile,"/pics/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink("/pics/".$picfile);
echo $available = "image is available.";
$sql = ("DELETE FROM $table WHERE id=$delete");
$result = mysql_query($sql);
if ($result){
echo "Your Picture has been removed from our system.";
Die($available);
}
else{
echo "There was an error in removing your picture.";
$Delete = "";
Die();
}
}
else{
echo $available = "image is not available.";
}
}
The weird part is a have almost the same code in a delete button on my control panel located in "/adminpanel" and it works perfectly. The code for that is the same except I use $id instead $delete and "../" before all the "pics/" because it's in the adminpanel folder. The permissions are right and the folder exists because the code works with that page. And I know $delete is getting set because the record gets deleted from the database. I know picfile, author and title are getting set because I appended them to the print statement and they were all right. Really confused. Any ideas?
Here is the code for the working page
q = ("select picfile,title,author from $table where id=$id");
$file=mysql_query($q);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
copy("../pics/".$picfile,"../pics/deletedrecordpics/".$author." - ".$title." - ".$picfile);
unlink("../pics/".$picfile);
$file=mysql_query($q);
$q = ("DELETE FROM $table WHERE id=$id");
$file=mysql_query($q);
why is this line repeated twice $file=mysql_query($q); ?
Try this
$file_path = $_SERVER["DOCUMENT_ROOT"]."/pics/";
if (file_exists($file_path.$picfile))
{
copy($file_path.$picfile, $file_path."/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink($file_path.$picfile);
}
else
{
echo "File not found!!!!!!!!";
}
can somebody help me for my codes. i can delete the image in the database but in the directory i can't. im tried for long hours but it seems not work at all. would somebody help me please? here's my code: this is the code where the images
<?
//this is were images displayed
$query = "SELECT * FROM images WHERE category='home'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
?>
<img src="images/template/delete.png" id="AEDbutton">
echo "<img border=\"0\" src=\"".$row['image']."\" width=\"200\" height=\"100\">";
echo "<br>"; }
?>
,?
include('global.php');
//this is were image were deleted
if($delete != "")
{
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
//but in here , it cannot delete image through directory
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result)) {
$image = $delete['image'];
$file= '/.directory/'.$image;
unlink($file);
}
?>
You already deleted the image entry in table, after that you try to get the same entry in DB. so, first you can delete the image from folder after that you can delete in the table.
<?php
include('global.php');
if($delete != "") {
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result)) {
$image = $delete['image'];
$file= '/.directory/'.$image;
unlink($file);
}
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
?>
Note:
Make sure your path $file= '/.directory/'.$image; is correct, I think it referring from root directory.
Funny. That's because you are first deleting the image id from the database and after that you are trying to get the ID of the previously deleted image (which no longer exists) and delete the file associated with it. Switch the code like this.
include('global.php');
if($delete != "")
{
//first delete the file
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result))
{
try
{
$image = $delete['image'];
$file= '/images/'.$image;
unlink($file);
} catch (Exception $e) {
}
}
// after that delete the id from the db of that image associated with the deleted file
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
UPDATE: I added a try catch
If you are deleting images, first you need to delete image and then delete in DB