PHP - How To Delete An Image From The Database And Folder In Php
I have a PHP CRUD application and when i delete a row i need it to delete from the MySQL and the image from the uploads folder as well. I have researched and tried dozens of ways with the unlink option but nothing works. If i take out the unlink from my code it will delete fine from the DB. I am new to coding and PHP so any help would be awesome. The file_path is correct. The uploads is the name of the folder where the image is stored and the $_POST["image"] is the column name in MySQL where the image name is stored. delete.php <?php //start PHP session session_start(); if (!isset($_SESSION['success'])) { header("Location: login_page.php"); die(); } // check if value was posted if($_POST){ // include database and object file include_once 'config/database.php'; $file_path = 'uploads/' . $_POST["image"]; if(unlink($file_path)) { // delete query $query = "DELETE FROM myDBname WHERE id = ?"; $stmt = $con->prepare($query); $stmt->bindParam(1, $_POST['object_id']); } if($stmt->execute()){ // redirect to read records page and // tell the user record was deleted echo "Record was deleted."; }else{ echo "Unable to delete record."; } } ?> this is the delete button code echo "<a delete-id='{$id}' class='btn btn-danger delete-object'>"; echo "<span class='glyphicon glyphicon-remove'></span> Delete"; echo "</a>"; This is the javascript for the delete button as well. // delete record $(document).on('click', '.delete-object', function(){ var id = $(this).attr('delete-id'); bootbox.confirm({ message: "<h4>Are you sure?</h4>", buttons: { confirm: { label: '<span class="glyphicon glyphicon-ok"></span> Yes', className: 'btn-danger' }, cancel: { label: '<span class="glyphicon glyphicon-remove"></span> No', className: 'btn-primary' } }, callback: function (result) { if(result==true){ $.post('delete.php', { object_id: id }, function(data){ location.reload(); }).fail(function() { alert('Unable to delete.'); }); } } }); return false; });
If you need any other info that would help you help me just let me know and i will get that in here ASAP. Thanks again for any help on this. Similar TutorialsHello
I am new here, and so i am to php.. i have a small question - i think anyone here could help me, im sure :-)
I have a php-gallery running locally on my desktop (using xampp), the gallery just shows images from a directory where a webcam saves its pictures in it (the gallery is named "ubergallery" - maybe anyone knows this gallery).
Now i really would like to have following option:
- A Button on the thumbnail called "delete" - when clicking on it, the picture should get replaced with another, predefined, placeholder-picture. I really hope somebody here can help me ! Thank you so much for your time !
I have attached the files!
Attached Files
UberGallery.php 37.81KB
0 downloads
index.php 2.81KB
0 downloads
index.php 663bytes
0 downloads Help me. What I am doing is editing a form with checkboxes... and updating image .. I uploaded scripts I want to delete old jpeg file from thumb folder and update new filename in db Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <script type="text/javascript"> function show_confirm() { var r=confirm("Delete?"); if (r==true) { //javascript:window.location='view.php'; alert("Deleted!!"); } else { //javascript:window.location='view.php'; alert("You pressed Cancel!"); return false; } } </script> </head> <body> <?php require("connect.php"); if ($_REQUEST['submit']) { $id=$_POST['hide']; for($i=1; $i<=$id; $i++) { $query2 = mysql_query("SELECT * from stu_detail WHERE id = $id "); while($file = mysql_fetch_array($query2)) { $unlink = unlink("up_images/thumb/" . $file['filename']); } } $new_name=$_POST['name']; $new_email=$_POST['email']; $new_phone=$_POST['phone']; $new_gender=$_POST['rad']; $new_city=$_POST['city']; $new_lang=implode(",",$_POST['chk']); $tar = "c:/wamp/www/rms/vignesh_2/up_images/"; if ($_FILES['efile']['error'] > 0) echo "Error" . $_FILES["efile"]["error"]; else { if (file_exists ("$tar" . $_FILES['efile']['name'])) { echo $_FILES['efile']['name'] . " already exsists"; } else { move_uploaded_file ($_FILES['efile']['tmp_name'],"$tar" . $_FILES['efile']['name']); } } $qry=mysql_query("UPDATE stu_detail SET name='".$new_name."', email='".$new_email."', phone='".$new_phone."', gender='".$new_gender."', city='".$new_city."', lang='".$new_lang."', filename='".$_FILES['efile']['name']."' WHERE id=$id ") or die(mysql_error()); require_once("create_thumb.php"); echo generateThumbs(); if (!$qry) { echo "not updated"; } else { echo "<table align='center' border='1' width='800' height='600'>"; ?><tr> <th scope="col">Name</th> <th scope="col">E-mail Address</th> <th scope="col">Phone</th> <th scope="col">Gender</th> <th scope="col">City</th> <th scope="col">Language</th> </tr> <?php $recyc=mysql_query("SELECT * FROM stu_detail where status = 1") or die(mysql_error()); $del = mysql_num_rows($recyc); if ($del != 0) echo "<a href='recycled.php'>Recycle bin</a>"; if ($qry2=mysql_query("SELECT * FROM stu_detail where status = 0 order by id desc") ) { while($res=mysql_fetch_array($qry2)) { ?> <tr> <td><?php echo $res['name']; ?></td> <td><?php echo $res['email']; ?></td> <td><?php echo $res['phone']; ?></td> <td><?php echo $res['gender']; ?></td> <td><?php echo $res['city']; ?></td> <td><?php echo $res['lang']; ?></td> <td> <img src="up_images/thumb/<?php echo $res['filename']; ?>" /> </td> <td> <a href="edit.php?uid=<?php echo $res['id']; ?>">edit</a></td> <!--<td><button type="button" onClick="return show_confirm();">Delete</button> </td>--> <td> <a href="delete.php?uid=<?php echo $res['id']; ?>" onClick="return show_confirm();">delete</a></td> </tr> <?php } } ?> </table> <?php } } ?> </body> </html> hi all i need a script that will allow me upload images to 2 dif folders on my server and then add the info to my database along with some other form data. iv been looking all over for code or scripts for days now and have been playing with cut and copyed code but no look again any help i will be greatful for as im a noob to php but al learning quick here is my html form Code: [Select] <html> <body> <form action="add.php" method="post"> Project Name: <input type="text" name="pro_name" /><br> Thumbnail: <input type="file" name="thumbnail" /><br> ////// this image to ../thum Short Details: <input type="text" name="short_details" /><br> Full Details: <input type="text" name="full_details" /><br> Category: <input type="text" name="cat" /><br> Image1: <input type="file" name="image1" /><br>//// and image1,2,3,4 to ../images Image2: <input type="file" name="image2" /><br> Image3: <input type="file" name="image3" /><br> Image4: <input type="file" name="image4" /><br> <input type="submit" /> </form></body></html> here is my code for add.php witch only adds the info to the DB Code: [Select] <?php error_reporting(E_ALL); include ("../includes/db_config.php"); $con = mysql_connect($db_hostname,$db_username,$db_password); @mysql_select_db($db_database) or die( "Unable to select database"); $sql="INSERT INTO $db_table (pro_name, thumbnail, short_details, full_details, cat, image1, image2, image3, image4) VALUES ('$_POST[pro_name]','$_POST[thumbnail]','$_POST[short_details]','$_POST[full_details]','$_POST[cat]','$_POST[image1]','$_POST[image2]','$_POST[image3]','$_POST[image4]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> hello friends, while clicking the form all the information goes to database, I have one image upload field, when cliking the submit button, i would like 'image name' to go in database and file to go in /upload folder, i have tried this for hours and gave up, if anyone help me in this, i would be very greatful I am looking to resize the images (hight and width) after I have uploaded to a folder with php. What the bast way to do this. I am unable to resize them before I upload as I use the same picture in other areas. I'm using this code to view the image and other infomation on the database can some one point me in the right direction or show me how to change the code below. Thanks Code: [Select] <?php mysql_connect("localhost", "", "") or die(mysql_error()) ; mysql_select_db("stafflog") or die(mysql_error()) ; $data = mysql_query("SELECT * FROM ********") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { echo "<img src=http://www.web.com/productimages/" .$info['image'] . "> <br>"; echo "<b>Name:</b> ".$info['yourname'] . "<br> "; echo "<b>price:</b> ".$info['price'] . " <br>"; echo "<b>shortdes:</b> ".$info['shortdes'] . " <hr>"; } ?> Hey, i need help storing an image in my database via the URL(image location) at the moment my php code is storing the image in a folder on the directory called upload. here is the code: <?php // Where the file is going to be placed $target_path = "upload /"; /* Add the original filename to our target path. Result is "uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); $target_path = "upload/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> Click <a href="products.php">HERE</a> to go back to form if someone could help me i'd be very grateful I have made a file explorer for my site so i can upload files, delete them and rename them. Everythings working fine except when i want to delete a folder. I realise you cant use ftp_delete, coz' that only works for files. I have tried rmdir, and even though I am getting no errors, it seems to do nothing :s So what is the best way to delete a folder and its contents using PHP FTP commands? Thanks guys how do i make this part of the script delete the folder and contents. Code: [Select] <?php $path = "../../gallery/gallery_files/gallery/"; if(isset($_POST['file']) && is_array($_POST['file'])) { foreach($_POST['file'] as $file) { rmdir($path. "/" . $file) or die("Failed to delete file"); } } ?> Hi,
I wish to find out is there any possible that I can delete some data inside my php website but inside my sql database, the record will still at there?
Thank you.
Hi.. I've seen code for back up database but when I run the code the database was backup outside the folder. I want to put the back up database inside the folder here is the code: Code: [Select] <?php include 'config.php'; backup_tables('localhost','root','','payroll'); /* backup the db OR just a table */ function backup_tables($host,$user,$pass,$name,$tables = '*') { $link = mysql_connect($host,$user,$pass); mysql_select_db($name,$link); //get all of the tables if($tables == '*') { $tables = array(); $result = mysql_query('SHOW TABLES'); while($row = mysql_fetch_row($result)) { $tables[] = $row[0]; } } else { $tables = is_array($tables) ? $tables : explode(',',$tables); } //cycle through foreach($tables as $table) { $result = mysql_query('SELECT * FROM '.$table); $num_fields = mysql_num_fields($result); $return.= 'DROP TABLE '.$table.';'; $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table)); $return.= "\n\n".$row2[1].";\n\n"; for ($i = 0; $i < $num_fields; $i++) { while($row = mysql_fetch_row($result)) { $return.= 'INSERT INTO '.$table.' VALUES('; for($j=0; $j<$num_fields; $j++) { $row[$j] = addslashes($row[$j]); $row[$j] = ereg_replace("\n","\\n",$row[$j]); if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; } if ($j<($num_fields-1)) { $return.= ','; } } $return.= ");\n"; } } $return.="\n\n\n"; } //save file $myfoldername = "backup_DBPayroll";//your folders name $handle = fopen(getcwd().$myfoldername.'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+'); // $handle = fopen('db-backup-'.date('m-d-Y').'-'.(md5(implode(',',$tables))).'.sql','w+'); fwrite($handle,$return); fclose($handle); } $smarty->display('header_cat.tpl'); $smarty->display('backup.tpl'); $smarty->display('footer.tpl'); ?> Thank you in advance I have been looking around and have not been able to find any useful information on this. I am trying to transfer files from a folder in the directory to a table in a database. Eventually they will be images but for right now I am just trying to get text files to transfer. Any help/code/ideas would be a lot of help. This is going to be triggered a button on a page by the way. I have this script from http://lampload.com/...,view.download/ (I am not using a database) I can upload images fine, I can view files, but I want to delete them. When I press the delete button, nothing happens
http://www.jayg.co.u...oad_gallery.php
<form>
<?php $dir = dirname(__FILENAME__)."/images/gallery" ; $files1 = scandir($dir); foreach($files1 as $file){ if(strlen($file) >=3){ $foil = strstr($file, 'jpg'); // As of PHP 5.3.0 $foil = $file; $pos = strpos($file, 'css'); if ($foil==true){ echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />'; echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host //echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/ $file' /><br/>"; } } }?> <input type="submit" name="mysubmit2" value="Delete"> </form>
any ideas please?
thanks
Hi guys, I am recent working on my php to delete the information in a database. When I insert the value in the url bar something is like: www.mysite.com/delete.php?myfavorites=what ever it is&user=test. When I inserted the value in the url bar, it did not search for the value in a database to delete it while match with the username in the url bar. Code: [Select] <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); define('DB_DATABASE', 'mydbname'); $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $favorites = clean($_GET['favorites']); $username = clean($_GET['user']); if($favorites == '' && $username == '') { // both are empty $errmsg_arr[] = 'Favorites are missing.'; $errflag = true; if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['favorites'])) { $insert[] = 'favorites = \'' . clean($_GET['favorites']) . '\''; } if(isset($_GET['username'])) { $insert[] = 'username = \'' . clean($_GET['username']) . '\''; } if (count($insert)>0) { $names = implode(',',$insert); if($favorites && $username) { mysql_query("DELETE valuedata FROM favorites WHERE username='$username'"); $deleted = mysql_affected_rows(); if($deleted > 0) { echo("The value in favorites are deleted"); } else { echo("failed"); } }else{ echo("failed"); } } } mysql_close($link); ?> If you know how to delete the value in a database for each row while it match with the username in the url, please say so as i would like to know how to do it. Any advise would be much appreciated. Thanks, Mark Hi guys, I need a bit of your help. I have successfully deleted a row in a database after I have inserted the value name with a var function that match with a username in the url bar. Now I would like to delete more than one row, but I don't know how to do this? What I am trying to achieve is to enter the url something like this: www.mysite.com/delete.php?favorites=the value1&use=test It will search for a value in the database and then delete it. But if I add the &favorites=the value2 or more than 2, then search for the values in each row while looking for a username before delete the rows Here's the current code: Code: [Select] <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); define('DB_DATABASE', 'mydbname'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $favorites = clean($_GET['favorites']); $username = clean($_GET['user']); if($favorites == '' && $username == ''){ // both are empty $errmsg_arr[] = 'Both name and email are missing. You must enter one or the other.'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['favorites'])) { $insert[] = 'favorites = \'' . clean($_GET['favorites']) . '\''; } if(($favorites) && isset($username)) { mysql_query("DELETE FROM favorites WHERE username='$username' AND favorites='$favorites'"); $deleted = mysql_affected_rows(); if($deleted > 0) { echo "favorites rows is deleted"; } else { echo("favorites are already deleted"); } } } ?> Any advice would be much appreciated. Thanks, Mark Hey guys, i'm new to this site and would need some help with coding. So i'm making a car part website which should has brand/model search. It's a dropdown search which will get the brand / model from database and should display all the parts for that exact model, from folder. Database structure which i have is id, master, name. ( Here's some pictures to clear out what i'm doing. http://imgur.com/a/7XwVd ) So the problem is that it does not get the images from folder named ex: *_audi_a3.jpg. And link to codes what have been written already. Parts.php: http://pastebin.com/q6vdypge Update.php: http://pastebin.com/DymhGQ17 Search_images.php: http://pastebin.com/LF5Q0i8f Core.js: http://pastebin.com/bgc0y4TS I don't know what's wrong with it sadly. One thing i noticed when i used firebug it gives error on category when searching error:true. Hope you guys understand what i mean here, and also all help is appreciated. And move this post if it's in wrong place. Thanks! Edited by aeonius, 17 October 2014 - 12:15 PM. Basically i have a folder with 100+ images they are NOT all the same extension, what im wanting to do is use PHP to find all the images and put them all in a database. how would i go about doing this? thanks I'm working on an old cms I built a few years ago and for some reason my Delete page isn't working. It has to be something simple I'm overlooking. The database connection is made just above this code and is pulling the thumb and title listed by id. When I push delete I'm getting the cmd=delete&id=2 passed on so something is up with my last if statement (I think). Here is the code: if(!isset($cmd)) { //display all the news $result = mysql_query("select * from verizon order by id"); //run the while loop that grabs all the news scripts while($r=mysql_fetch_array($result)) { //grab the title and the ID of the enws $title=$r["title"];//take out the title $id=$r["id"];//take out the id $thumb=$r["thumb"]; echo "<div id='delete'> <table> <tr> <td width='350px'><strong>$title</strong></td><td><a href='verizondelete.php?cmd=delete&id=$id'> Delete</a></td> </tr> <td colspan='2' align='center'><img src='../upload/verizon/$thumb'></td> </table> </div><br />"; } } if($cmd=="delete") { $sql = "DELETE FROM verizon WHERE id='$id'"; $result = mysql_query($sql); echo "<h1 style='text-align:center;'>deleted!</h1>"; } } ?> I am trying to find a way of deleting entries from a database after a certain time, and also when there is another field in the database set to 0. i have got so far with the code (will delete when other field is at 0) but nothing happens when i try to add in the time. my code im trying to use is below mysql_query("DELETE FROM temp_users WHERE book_stage='0' and WHERE time() > [creation+60]"); creation being the name of the field in the database that holds the unix time stamp of when the entry was created. i need the entry to be deleted one hour after it was created if the book_stage hasnt been changed to 1 during this hour. many thanks, gavin i trying to delete messages out of my message database but im not sure if i'm using this code right or there stuff missing to it :S delete.php <?php require_once('settings.php'); checkLogin('1 2'); $id=$_GET["msgs"]; mysql_query("DELETE messages FROM messages WHERE message_id='$id'"); ?> link usages to delete <a href="delete.php?msgs=<? echo $row['message_id'] ?>">[X]</a> Hello i have a text box and a button on my webpage and want to get the text box to find the username i type into it from the database and when it does it will then go to number and delete any text that is under usernames number field as you can see i have no idea how. Code: [Select] $result = mysql_query("DELETE FROM mytable WHERE username='$username1' AND number='$number1'" ); Code: [Select] <form name="form1" method="post" action="p.php"> <p><input type="submit" value="Enter" /></p> <input name="username" type="text" id="username" size="15" maxlength="35" value="<?php echo $username1; ?>" /> </form> |