Delete image and copy from gallery - php

I have a gallery that I'm able to upload images with a title and a short description about the image. I store the images in a folder on my ftp and the data in a database. Here is a screen shot of the database.
I want to give my client a little more control over the gallery by allowing them to update the gallery and delete posts in the gallery. Right now I want to focus on the DELETING part.
I'm using the following code to try and delete the images/post by trying to select by id and delete.
When executing the delete script on the site I get no errors on the page or on my ftp, but the image does not delete.
The end result I'm looking for would be to have the row deleted from the table and the image deleted from the ftp.
I'm very new to php and know I need to learn much more about it, but if someone could help out I would appreciate it. I apologize for the code dump, but not sure how to ask the question without showing what I'm working with.
DELETE CODE:
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//deleting the row from table
$result=mysql_query("DELETE FROM images where id='$id' limit 1;");
//redirecting to the display page (index.php in our case)
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>
This is the code I'm using to to access the image on the modify-gallery page
modify-gallery code:
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
/* be safe, not sorry */
foreach ($_REQUEST as $k => $v) {
$_REQUEST[$k] = mysql_real_escape_string($v);
}
/* take cat from url if exists */
$category = #$_REQUEST["category"] ? $_REQUEST["category"] : null;
$images = mysql_query(
$category ?
sprintf(
"SELECT * FROM images WHERE data_type = '%s'",
$category
) :
"SELECT * FROM images"
);
if ($images) {
$total = mysql_num_rows($images);
if ($total) {
$per = 12;
$page = #$_REQUEST["page"] ? $_REQUEST["page"] : 1;
$pages = ceil($total/$per);
}
mysql_free_result($images);
}
?>
and then this is used to display the images/posts and lists the delete and update button..(same page)
<div class="row">
<ul id="stage" class="portfolio-4column">
<?php
if ($category) {
$images = mysql_query(sprintf(
"SELECT * FROM images WHERE data_type = '%s' ORDER BY id DESC LIMIT %d, %d",
$category, ($page - 1) * $per, $per
));
} else $images = mysql_query(sprintf(
"SELECT * FROM images ORDER BY id DESC LIMIT %d, %d",
($page - 1) * $per, $per
));
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>" data-type="<?=$image["data_type"] ?>">
<div class="grid_3 gallerybox-admin">
<div class="overallheight-admin">
<div class="gallerybox-admin"><a class="fancybox" rel="<?=$image["data_type"] ?>" href="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/gallery/<?=$image["file_name"] ?>" title="<?=$image["title"] ?>">
<img src="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/gallery/<?=$image["file_name"] ?>" alt="<?=$image["title"] ?>" class="max-img-border"></a></div>
<div class="galleryh"><?=$image["title"] ?></div>
<div class="galleryp"><?=$image["description"] ?></div>
</div>
<div class="grid_1"><h4 class="btn-green">Delete</h4></div>
<div class="grid_1"><h4 class="btn-green">Update</h4></div>
</div>
</li>
<?php
}
?>
</ul>
</div>
Code from Stack Overflow (Currently Using):
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//Select image_name(if not known)
$img = mysql_query("Select file_name from images where id=\"$id\"");
$img_res = mysql_fetch_array($img);
$filename = $img_res[0];
unlink($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $filename);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id=\"$id\" limit 1;");
//redirecting to the display page
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>

fix this in delete button html, to pass the file name by the url
<h4 class="btn-green">Delete</h4></div>
In your remove.php
include("/connections/dbconnect.php");
$filename = isset($_GET['value']) ? $_GET['value'] : NULL;
if (!empty($filename)) {
$delete = unlink("images/gallery/" . $filename);
if($delete){
$result = mysql_query("DELETE FROM images where file_name="'. mysql_real_escape_string($filename)."' limit 1;")";
header("Location:succes_page.php");
}else{
header("Location:failure_page.php");
}
}else{
header("Location:failure_page.php");
}
side note try to update your mysql_* functions to PDO or mysqli

"The end result I'm looking for would be to have the row deleted from the table and the image deleted from the ftp."
the row deleted from the table ✓
But you still need to remove the actual file from your server to do so use unlink($fileName);
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
// Delete the file from the server
unlink($_SERVER['DOCUMENT_ROOT'] . "{Path Where Your Images stored}" . $row['file_name']);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id='$id' limit 1;");
As you can see I used the $row['file_name'] to get the file name from you database (good to show us your table structure)

To delete a file from the ftp you should use
unlink(filename with complete path);
Complete Code:
//Change Delete code to following
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//Select image_name(if not known)
$img = mysql_query("Select image_name(your column) from images where id=\"$id\"");
$img_res = mysql_fetch_array($img);
$filename = $img_res[0];
unlink("path to file".$filename);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id=\"$id\" limit 1;");
//redirecting to the display page (index.php in our case)
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>

Related

Display Images From a Local Directory in PHP

I am trying to get the File Name of the Images form database and want to insert in a page. I am inserting images to a local folder and store the names in the database. Need to retrieve it and.
<?php
global $DBConnect;
$Query = "SELECT * FROM posts ORDER BY datetime DESC ";
$Execute = mysqli_query($DBConnect,$Query);
while ($DataRows = mysqli_fetch_array($Execute)){
$PostID = $DataRows["id"];
$DateTime = $DataRows["datetime"];
$Category = $DataRows["category"];
$Author = ["author"];
$Image = ["image"];
$Post = $DataRows["post"];
?>
<div class="thumbnail">
<img src="uploads/<?php echo $Image;?>">
</div>
<?php }?>
I didn't fetch the image using $DataRows. Its was my Mistake..!
$Image = $DataRows["image"];

img src showing wrong user from database

UPDATE I added this to my while loop during the array fetch. Does this work, or is there a better way? It is showing the correct pic now:
$query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
if($username == $row['username']) { //<--- NEW CODE
$profile_pic = '<img src="' . $row['avatar'] . '" style = "width:70%" alt="Profile Photo"/>';
}
}
}
I tried to search for this, but couldn't find anything similar. I've edited nothing on my profile.php page. I created several test users to test the functionality of a live user search. Everything was working fine until I logged in as another user. The profile pic that is displayed in the browser is pointing to a different user, yet the real image path is correctly stored in the database. I deleted all users except for the original two, and nothing has changed. I haven't changed any code, but I will show the relevant code that displays the profile pic and the live search.
(Note: I will work on more secure queries later. Learning to translate into prepared statements as I go.)
The pic container from profile.php. I'm even echoing the current username temporarily at the top left just to show that it's getting the correct name.
<div id="avatar-container" class="dsh-display-container">
<button type="button" id="upload-toggle"><i class="fa fa-camera"></i><span> Update Avatar </span></button>
<?php
$query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$profile_pic = '<img src="' . $row['avatar'] . '" style = "width:70%" alt="Profile Photo"/>';
}
}
?>
<?php echo $avatar_form; ?>
<?php echo $profile_pic; ?>
</div>
This is what is displaying on my profile:
On my search.php page, it displays correctly.
This is what shows the info:
try {
$db = new PDO("mysql:host=localhost;dbname=devSocial", "xxxxxxxxx", "xxxxxxxxxxxxx");
} catch(Exception $e) {
die("ERROR: ".$e->getMessage());
}
if (isset($_POST['username']) && $_POST['username'] != "") {
$req = $db->prepare("SELECT * FROM `users` WHERE username LIKE :username");
$req->execute(array(
'username' => '%' . $_POST['username'] . '%'
));
if ($req->rowCount() == 0) {
echo "Sorry. No one by that name found.";
} else {
while ($data = $req->fetch()) {
$data['gender'] = ($data['gender'] == 'm') ? 'male' : 'female';
?>
<div class="user">
<div class="img-container">
<img src="<?php echo $data['avatar']; ?>" class="userImage">
</div>
<span class="username"><?php echo $data['username']; ?></span><br/>
<span class="gender"><?php echo $data['gender'];?></span><br/>
<span class="profession"><?php echo $data['profession']; ?></span><br/>
<span class="uni"><?php echo $data['uni']; ?></span><br/>
<span class="degree"><?php echo $data['degree']; ?></span><br/>
<span class="major"><?php echo $data['major']; ?></span><br/>
<hr/>
</div>
I completely removed testUser from the database, and the profile displays correctly.
My main concern is that I changed nothing in those two segments of code and I was able to alternate between users. What is this voodoo? I've logged in as the two different users off and on for weeks and it showed correctly. I even went over my local history with a fine toothed comb and nothing has been changed. If someone could help that would be great because I've spent far too long. If I delete all but my "csheridan" user, it works. If I delete then recreate the testUser, my "csheridan" user now shows the default avatar. This is a major bug and I'm lost.
Your photo query is getting all your users:
$query = "SELECT * FROM users";
This needs to be fixed
The user never returned to post his comment as an answer, so I'll post it here. It was actually a combination of comments.
When I ran my query
$query = "SELECT * FROM `users`";
it gets all users from the DB. And during my original while loop
while($row = mysqli_fetch_assoc($result) {
$profile_pic = '<img src="' . $row['avatar'] . '" style="width:70%" alt="Profile Photo"/>';
it was always returning the last user in the database.
This is what fixed it. I added an if condition to match the row specifically to the current username:
$query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
if($username == $row['username']) { //<-- THIS RIGHT HERE
$profile_pic = '<img src="' . $row['avatar'] . '" style = "width:70%" alt="Profile Photo"/>';
}
}
}
echo $avatar_form;
echo $profile_pic;
If any people search for this question, please use more secure code. I'm learning PDO and prepared statements, and the code will be replaced with it later.

How to remove a row from MySQL table data using html delete button in PHP

I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}

Select query to match to columns

I am trying to create a user profile image feature. So far I am able to upload and select an image and display it, but I cannot figure out how to select the image specific to a user. My query was working (though with the issue described above) until I added the code below (//added is what I changed).
I was able to get my insert query to send the user's user_id with it, I just cannot figure out the select part.
My database for this is small, it just has id, user_id, img.
I want to select the img that is in my database that has the user's user_id. I am carrying the user_id with a session and that is what $user_id is.
Anyone see what I am doing wrong in my select query?
function getPhoto($con,$dest)
{
$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" ); //added
// $result = mysqli_query($con,"SELECT * FROM `profile_img` where `img` = '$dest'");
$result = mysqli_query($con,"SELECT * FROM `profile_img` where `img` = '$user_id'"); //added
if($row = mysqli_fetch_array($result))
return $row;
return 0;
}
Edit: More code.
function getPhoto($con,$dest)
{
$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" ); //added
// $result = mysqli_query($con,"SELECT * FROM `profile_img` where `img` = '$dest'");
$result = mysqli_query($con,"SELECT * FROM `profile_img` where `user_id` = '$user_id'"); //added
if($row = mysqli_fetch_array($result))
return $row;
return 0;
}
// Make sure all functions above are include here
// Get the database connection
$con = Connection();
// Check for post
if(isset($_POST['create'])) {
// Try uploading
$upload = UploadFile($_FILES);
// If upload fails
if(!$upload['success'])
echo '<h3>Sorry, an error occurred</h3>';
else {
// You could add error handling here based on the results of
// each function's success or failure below.
// Try to save it
$saveToDb = SaveToDb($con,$upload['file']['dest']);
// Get the profile from image name
$profPic = ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false; ?>
<?php
}
}
?>
<img id="profile-pic" src="<?php echo (!empty($profPic) && $profPic != 0)? $profPic['img'] : "profile_images/default.jpg"; ?>" alt="<?php echo (!empty($profPic) && $profPic != 0)? "Profile Picture" : "No Picture"; ?>" />
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file" class="inputbarfile" onchange="readURL(this);">
<img width="400px" height="300px" id="file" src="#" alt="your image">
<input type="submit" name="create" id="signinButton" value="Upload">
</form>
This:
$result = mysqli_query($con,"SELECT * FROM `profile_img` where `img` = '$user_id'"); //added
Should be:
$result = mysqli_query($con,"SELECT * FROM `profile_img` where `user_id` = '$user_id'"); //added
Because img column holds the image path and you are comparing user id.

PHP Get method not working

I am able to retrieve the name but why can't I show the whole video inside the embed location?
This is the the whole PHP file that I am working on.
The first box is mainly about uploading the video on to the directory and database.
I am actually having problem with the second box only as the video does not appear.
<?php
include 'connect.php'; //include the php file into this php file
?>
<div id="box">
<form method='post' enctype="multipart/form-data">
<?php
if(isset($_FILES['video'])){
$name = $_FILES['video']['name'];
$type = explode('.', $name);
$type = end($type);
$size = $_FILES['video']['name'];
$random_name = rand();
$tmp = $_FILES['video']['tmp_name'];
if($type != 'mp4' && $type != 'mp4' && $type != 'wmv'){
$message = "Video Format Not Supported!";
}
else {
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$type);
mysqli_query($db, "INSERT INTO videos (id, name, url)
VALUE ('', '$name', '$random_name.$type')");
$message = "Successfully Uploaded!";
}
echo "$message";
}
?>
Select Video : <br/>
<input type='file' name="video" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
</div>
<div id="box">
<?php
$query = mysqli_query($db, "SELECT `id`, `name`, `url` FROM videos");
while($run = mysqli_fetch_array($query)){
$video_id = $run['id'];
$video_name = $run['name'];
$video_url = $run['url'];
?>
<?php
echo $video_name;
?>
<?php
$video = $_GET['video'];
echo "<embed src=`$video` width='560' height='315'></embed>" ;
?>
<?php
}
?>
</div>
You have backticks instead of quotes in your HTML. Change them to single or double quotes, e.g.:
echo "<embed src='$video' width='560' height='315'></embed>" ;
^ ^
You should have
if (isset($_GET['video'])) {
$video = $_GET['video'];
echo '<embed src="'.$video.'" width="560" height="315"></embed>';
}
So people can't access the page without entering a video id
Try this way, it will require you to change your database. But should work. Just read the commented out instructions I made to use it.
<div id="box">
<?php
if (isset($_GET['video'])) {
$video = $_GET['video'];
$query = mysql_query("SELECT * FROM `videos` WHERE `id`='$video'");
$count = mysql_num_rows($query);
if ($count!=0) {
$row = mysql_fetch_assoc($query);
$video_id = $row['id'];
$video_name = $row['name'];
$video_url = $row['url'];
echo $video_name;
echo '<embed src="'.$video_url.'" height="315px" width="560px">';
//echp <video height="315px" width="560px" controls><source src="movie.mp4" type="video/mp4"></video>
//Use the above code if you want a html5 video player.
} else {
echo 'Video does not exist!';
}
} else {
echo 'Please enter a video id!';
}
/*
How to use it:
Create a database called "videos"
Insert the following three columns:
id = varchar(225) as `primary_key`
name = varchar(225);
url = varchar(225);
To insert a video, you will need to create
a random id for the video and insert it
into the mysql database. Example
$rand = rand(111111111,999999999);
$id = md5($rand);
//example $id = 3174143713413051830531
$name = "Random video name";
$url = "http:/localhost/websitename/videos/nameofvideo.mp4";
$query = mysql_query("INSERT INTO `videos` VALUES ('$id','$name','$url')");
Then to select the video you will go to a page
video.php?video=[video id here];
video.php?video=3174143713413051830531
then the php will select the url for the video
id = 3174143713413051830531
and it will play that video.
example: video_url would be http://localhost/websitename/videos/nameofvideo.mp4
If you have any further questions,
feel free to ask me. Thanks
*/
?>
</div>
Hope this works. Thanks!

Categories