My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

How to delete images from database using php and mysql

Keerthi Kamarthi's photo
Keerthi Kamarthi
·Jan 16, 2018

I am trying to delete images from database using php, I added delete button to delete, but how can I give functionality to delete button, for the functionality I gave href tag to delete button, but web site delete button also treated as image. please help me to delete image from database using delete button.

index.php code:

<?php $con = mysqli_connect("localhost","root","","indishare"); // Check connection if (mysqli_connect_errno()) { die("Failed to connect to MySQL: " . mysqli_connect_error()); }

if (!$result = mysqli_query($con,"SELECT * FROM upload_img ORDER BY uploaded_on DESC")) { die("Error: " . mysqli_error($con)); } ?>

<?php if($result->num_rows > 0){ while($row = mysqli_fetch_array($result)) { $imageThumbURL = 'images/thumb/'.$row["file_name"]; $imageURL = 'images/'.$row["file_name"]; ?> <div class="del"> <a href="<?php echo $imageURL; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" > <img src="<?php echo $imageURL; ?>" alt="" /> </a> </div> <a href="del.php?id=<?php echo $row['id']; ?>" >Delete</a>

<?php } } ?>

del.php code:

<?php // Your database info $db_host = 'localhost'; $db_user = 'root'; $db_pass = ''; $db_name = 'indishare';

if (!isset($_GET['id'])) { echo 'No ID was given...'; exit; }

$con = new mysqli($db_host, $db_user, $db_pass, $db_name); if ($con->connect_error) { die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error); }

$sql = "DELETE FROM upload_img WHERE id = ?"; if (!$result = $con->prepare($sql)) { die('Query failed: (' . $con->errno . ') ' . $con->error); }

if (!$result->bind_param('i', $_GET['id'])) { die('Binding parameters failed: (' . $result->errno . ') ' . $result->error); }

if (!$result->execute()) { die('Execute failed: (' . $result->errno . ') ' . $result->error); }

if ($result->affected_rows > 0) { echo "The ID was deleted with success."; } else { echo "Couldn't delete the ID."; } $result->close(); $con->close();