I'm trying to delete specific images in a database through PHP.
I have a page where all images in the database are displayed and I wanted a button under each one of them so I could delete them individually through their id but I don't know how.
Here's the PHP code for showing all images:
<?php
$result = mysqli_query($con, "SELECT * FROM galeria");
?>
<h5>Images:</h5>
<?php
while ($row = mysqli_fetch_array($result)) {
?><h6> <?php echo $row['titleimg']; ?></h6>
<p><?php echo $row['events_id']; ?></p>
<img src="../images/<?php echo $row["img"]; ?>" width="301px" height="200px"/>
<form action="delete_images.php" method="post">
<input type="submit" name="delete" value="Delete" />
</form>
<?php
echo "<br>";
echo "<br>";
}
?>
So now, what's the code I should have in my "delete_images.php" file?
Your form needs an additional piece of information, an identifier for the image to be deleted. Something like:
<form action="delete_images.php" method="post">
<input type="hidden" name="id" value="<?php echo $row['img_id'] ?>" />
<input type="submit" name="delete" value="Delete" />
</form>
Naturally, I'm guessing on the column name (img_id), but any identifier for that specific image will do the trick. With that, your POST to delete_images.php will have that value (in $_POST['id']) and can use it in the DELETE query to the database.
Put a hidden input field that will contain the imageName to which you want to delete.
<input type="hidden" value="'.$row["img"].'" name="imageName" />
// Now write some server side code in delete_images.php that will delete file
if (array_key_exists('imageName', $_POST)) {
$filename = $_POST['imageName'];
if (file_exists($filename)) {
unlink($filename);
// Write Mysql query that will delete the row from database
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
Related
I have a list of items in one file (fruit.php):
<form action="delete_items.php" method="post">
<input type="radio" value="apple" name="fruit">Apple<br>
<input type="radio" value="pear" name="fruit">Pear<br>
<input type="radio" value="banana" name="fruit">Banana<br>
<input type="submit" value="delete" name="deleteButton"><br>
</form>
In the delete_items.php, I have a variable that stores the selection:
<?php
$selection = $_POST["fruit"];
echo "are you sure you want to delete it?";
echo '<form action="delete_confirmation.php" method="post"><br>';
echo '<input type="submit" name="deleteYes" value="Yes"><br>';
echo '<input type="submit" name="deleteNo" value="No"><br>';
echo '</form>';
?>
Than in the confirmation file (delete_confirmation.php):
<?php
include 'delete_items.php';
if($_POST["deleteYes"]){
$query = 'DELETE FROM databaseName WHERE fruitName="' . $selection . '"';
$result = mysqli_query($connection, $query);
if(!$result){
die("Delete after check query failed!");
} else {
echo "Delete after check query success!";
}
} elseif($_POST["deleteNo"]){
echo "The course was not deleted!";
}
?>
But the varibale $selection in the delete_confirmation.php file is always null even though i included the delete_items.php file (when i echo it, nothing is shown). Is there a way to pass the selection variable from delete_items.php to the delete_confirmation.php file?
For a file management I use a foreach loop in which all the files are displayed. Now I want foreach to delete files with $_POST.
When I echo pathinfo($dir.'/'.$file, PATHINFO_DIRNAME).'/'.$file; in the foreach near each file, it shows me the exact location of the files.
Now for each file I want do something like this in the foreach loop:
if(isset($_POST['delete'])) {
unlink($_POST['unlink']);
}
<form method="post">
<input type="hidden" name="unlink" value="<?php pathinfo($dir.'/'.$file, PATHINFO_DIRNAME).'/'.$file; ?>" />
<input type="submit" name="delete" value="Delete">
</form>
I know this is not correct but i hope you understand that what i want to achieve is clear.
How can I do this?
DISCLAIMER
The method outlined below is 100% insecure and if the code makes it into the public realm then you can kiss your server goodbye.
For deleting one file you can do this:
index.php
<form method="POST" action="delete.php">
<input type="hidden" name="delete_path" value="/path/to/your/file.pdf">
File.pdf <button type="submit">Delete</button>
</form>
delete.php
<?php
$delete_result = false;
$unlink_error = '';
if(isset($_POST['delete_path']) && is_file($_POST['delete_path']))
{
$delete_result = unlink($_POST['delete_path']);
$unlink_error = error_get_last();
}
if($delete_result)
{
echo 'Successfully deleted '.$_POST['delete_path'];
}
else
{
echo 'Uh oh, Spaghettios :(<br><br>';
echo 'Last known error<br>'.$unlink_error;
}
I am use path unlink(FILE)
echo $new_file_dert = FILE . '/'.$template_name;
<form method="post">
<input type="hidden" name="unlink" value="<?php echo $new_file_dert; ?>" />
<input name="delete" type="submit" class="btn-delete submitdelete" value="Delete">
</form>
<?php
echo $new_file_dert = FILE . '/'.$template_name;
if( isset( $_POST['delete'] ) ) {
unlink($_POST['unlink']);
}
I have written code to retrieve all the images from database for a specific city, and I want to be able to delete a specific image or to change the caption.
The problem is:
the code always work on the last image only!
I hope you guys will be able to help me with this problem.
Retrieve code:
<?php
$City_name=$_REQUEST['id'];
$Image_query = "SELECT * FROM image where City_name ='".$City_name."' ";
$Image_result = mysqli_query($dbcon,$Image_query);
echo "<table>";
while ($row = mysqli_fetch_array($Image_result))
{
$image_id = $row['Image_id'];
$image = $row['Image_url'];
$Caption = $row['Caption'];
echo "<tr style='float:right;'>";
echo "<td>"; ?> <img src="<?php echo $image ; ?>"/> <br>
<input type="text" name="caption" value="<?php echo $Caption ;?>" />
<br> <input name="delete" type="submit" value="Delete picture" />
<br> <input name="Update_caption" type="submit" value="change caption" />
<?php echo "</td>";
echo "<td>"; ?> <input class="input-image" type="hidden" name="id" value="<?php echo $image_id ;?>" />
<?php echo "</td>";
} /* End of while loop */
echo "</tr>";
echo"</table>";
?>
Update code :
if (isset($_POST['Update_caption'])) {
$ImageID = $_POST['id'];
$ImageCaption = $_POST['caption'];
$sql = mysqli_query ($dbcon,"UPDATE `image` SET `Caption`='".$ImageCaption."' WHERE `Image_id`='".$ImageID."' ");
if ($sql) {
echo "done";
} else { echo "error"; }
}
Delete code :
if (isset($_POST['delete'])) {
$ImageID = $_POST['id'];
$sql = mysqli_query ($dbcon,"DELETE FROM `image` where `Image_id` = '".$ImageID."' ");
if ($sql) {
echo "done";
} else { echo "error"; }
}
$_POST['id'] (sql injection alert!) contains the contents of the input element that has a name attribute id.
You are echoing out your input elements in a loop, all with the same name so the last one will overwrite all the previous ones.
You should use an array like for example:
<input class="input-image" type="hidden" name="id[<?php echo $image_id ;?>]" value="<?php echo $image_id ;?>" />
So that your $_POST['id'] is an array containing all elements.
The same applies to other input elements like the caption.
An alternative, especially for your delete option, would be to wrap every image in its own form. But keep in mind that you will need valid html for that to work, you can't have a form that opens in a row element and spans different columns.
And note that you should really use a prepared statement to close the sql injection hole you have now.
I have a few tables with image urls and image ids and I want to be able to delete from each of these tables using one php page and query.
The $tableToDeleteFrom is set as a variable in the url (ex delete.php?table=whatever)
$tableToDeleteFrom = $_GET['table'];
here is my query / php -- it appears this is where the problem may be, for some reason when $tableToDeleteFrom is not a variable, everything works fine. An image is deleted and the redirect brings is back to the correct page. However I need this to be dynamic because the user needs to be able to select which section they want to display in the url.
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM '.$tableToDeleteFrom.' WHERE id = ?');
$query->bindValue(1, $id);
$query->execute();
header('Location: img_delete_new.php?table='.$tableToDeleteFrom);
}
here is the php which fetches each line of the table and puts it into array to be accessed in the next bit of code:
class Image {
public function fetch_all() {
global $pdo;
$tableToDeleteFrom = $_GET['table'];
$query = $pdo->prepare("SELECT * FROM ".$tableToDeleteFrom);
$query->execute();
return $query->fetchAll();
}
}
$image = new Image;
$images = $image->fetch_all();
here is the form allowing user to select which image they want to delete:
<form action="img_delete_new.php" method="get">
<?php foreach ($images as $image) { ?>
<div class="delete">
<input type="radio" name="id" value="<?php echo $image['id']; ?>">
<img src="../images/thumbs/<?php echo $image['name']; ?>"><br>
<?php echo $image['desc']; ?>
</div>
<?php } ?>
<input type="submit" value="Delete Image" class="button">
</form>
updated the form to include the hidden variable "table"
<form action="img_delete_new.php" method="get">
<?php foreach ($images as $image) { ?>
<div class="delete">
<input type="hidden" name="table" value="<?php echo $tableToDeleteFrom;?>">
<input type="radio" name="id" value="<?php echo $image['id']; ?>">
<img src="../images/thumbs/<?php echo $image['name']; ?>"><br>
<?php echo $image['desc']; ?>
</div>
<?php } ?>
<input type="submit" value="Delete Image" class="button">
</form>
It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting