Deleting record from database with button in PHP - php

I have to delete a record from database using a button but my delete query does not work. Records are entered in database successfully with insertion query. I followed exact tutorial for php code available on YouTube "How to delete records from database with PHP & MySQL" by "kanpurwebD". The code in tutorial works fine but my code still does not delete record. (I have 2 records entered in database).
My code is as follows:
<div class="container">
<div class="row">
<form action='add_record.php' method='get'><button type='submit' name='id' value='submit' class='btn btn-default'>ADD RECORD</button><br />
</form>
<table class="table table-hover table-responsive">
<thead>
<tr>
<th>Topic #</th>
<th>Name</th>
<th>Admin ID</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
echo '<br />';
$query = "SELECT * FROM tb_topic";
$result = $con->query($query);
if(isset($_POST['submitDeleteBtn'])){
$key = $_POST['keyToDelete'];
$check = "Select * from tb_topic where topic_id = '$key'";
if(mysqli_num_rows($con, $check)>0){
$query_delete = mysqli_query($con,"Delete from tb_topic where topic_id = '$key'");
echo 'record deleted';
}
}
while($query_row = mysqli_fetch_array($result)) {?>
<tr>
<td><?php echo $query_row['topic_id'];?></td>
<td><?php echo $query_row['topic_name'];?></td>
<td><?php echo $query_row['aid'];?></td>
<td><input type = 'checkbox' name = 'keyToDelete' value = "<?php echo $query_row['topic_id'];?>" required></td>
<td><input type="submit" name="submitDeleteBtn" class="btn btn-danger"></td>
</tr>
<?php }
?>
</html>

I got it resolved by using following statement:
if(isset($_GET['delete'])) {
$page = filter_input(INPUT_GET, 'delete', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
$sql = "DELETE FROM tb_topic WHERE topic_id = $page";
}
$_GET() was not taking id as int so I tried typecasting it and it worked for me.

Related

Auto Incrementing value to be assigned as input then using value to delete item from database;

I am a student with a couple of weeks into PHP. What I am trying to do is Generate A table containing all users messages. Then I need a check box in each row. When the user hits the delete button rows with checkboxes marked will be deleted from table. The issue is that I can not figure out how to assign an individual value to each row of the HTML table to target with PHP. So I will only delete the rows that have been selected. I've only been able to delete all rows.
Here is what I got so far
<?php
//connect to database
include("../partials/.connect.php");
// select rows from contacts
$query = "SELECT * FROM contacts";
// display table headers
echo '<form>
<table width="100%" border="0" cellspacing="4" cellpadding="6">
<tr>
<th class="center">ID</th>
<th class="center">Name</th>
<th class="center">Phone</th>
<th class="center">Email</tdclass=center>
<th class="center">Message</th>
<th class="center"> <button type="submit" name="button1">Delete Selected</button</th>
</tr>';
// create loop to fetch all rows from DataBase
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["phone"];
$field4name = $row["email"];
$field5name = $row["message"];
// If delete button is clicked delete user
if(isset($_POST['button1'])) {
$sql = "DELETE FROM contacts WHERE id=$field1name";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
// display table data
echo '<tr>
<td class="center">'.$field1name.'</td>
<td class="center">'.$field2name.'</td>
<td class="center">'.$field3name.'</td>
<td class="center">'.$field4name.'</td>
<td class="center">'.$field5name.'</td>
<td class="center"> <input type="checkbox" id="if_checked" name="if_checked"></td>
</tr>
</form>';
}
$result->free();
}
?>
</body>
</html>
Your code is wrong, you just delete all your data along with your foreach run, so I just want to say keep learn more about programming logic since you're student
ok, for your question you have to put delete query before
$query = "SELECT * FROM contacts";
and your delete query should be based from foreach of checkbox value, and the most important thing is your checkbox name should be an array name since you will post multiple checkbox with the same name
<input type="checkbox" class="if_checked" name="if_checked[]">
and then you can use code like this
..................
include("../partials/.connect.php");
if(isset($_POST['button1'])) {
foreach($_POST['if_checked'] as $id) {
......your delete query
}
}
// select rows from contacts
$query = "SELECT * FROM contacts";
...................
You can use the checkbox as an array where you will store the ids when you select checkboxes for delete, you will loop through checkboxes and will be able to delete all selected rows.
I Was Able to solve this by storing the $row['id'] variable in the checkbox value instead of $Field1name. allowing me to specify which row to delete.
<?php
//connect to database
include("../partials/.connect.php");
// select rows from contacts
$query = "SELECT * FROM contacts";
//if delete button is set
if(isset($_POST['delete'])) {
$selected = $_POST['if_checked'];
//confirm record target
$confirm = mysqli_query($conn, "SELECT * FROM contacts WHERE id = '$selected'") or die("Not Found");
if(mysqli_num_rows($confirm)>0){
//record found delete
$delete_query = mysqli_query($conn, "DELETE from contacts where id = '$selected'")
or die("Not Deleted");
echo "<div><p>Record Deleted</p></div>";
} else {
//record not DataBase
die("Not deleted".mysqli_error());
}
}
// display table headers
echo '<form method="post" action="" role="form">
<table width="100%" border="0" cellspacing="4" cellpadding="6">
<tr>
<th class="center">ID</th>
<th class="center">Name</th>
<th class="center">Phone</th>
<th class="center">Email</th>
<th class="center">Message</th>
<th class="center"><input class="center" type="submit" name="delete" value="Delete"></th>
</tr>';
// create loop to fetch all rows from DataBase
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["phone"];
$field4name = $row["email"];
$field5name = $row["message"];
// If delete button is clicked delete user
// display table data
echo '<tr>
<td class="center">'.$field1name.'</td>
<td class="center">'.$field2name.'</td>
<td class="center">'.$field3name.'</td>
<td class="center">'.$field4name.'</td>
<td class="center">'.$field5name.'</td>
<td class="center">
<input type="checkbox" id="if_checked" name="if_checked" value="'.$row['id'].'"></td>
</tr>
</form>';
}
$result->free();
}
?>
</body>
</html>

MYSQL query in PHP is deleting all the rows in my table

I'm working on a PHP script that uses delete and I only want to delete 1 row. But everytime I tried to delete 1 row, the SQL executes but deletes the entire rows in the table.
The following is my PHP script
<table>
<tr>
<th>No.</th>
<th>Publisher Code</th>
<th>Publisher Name</th>
<th>City</th>
<th> </th>
</tr>
<!-- PHP FETCH/RETRIEVE FROM DB -->
<?php
include_once 'dbconnect.php';
$sql = mysqli_query($conn, "SELECT * FROM tbl_publisher");
$ctr = 1;
$record = mysqli_num_rows($sql);
if ($record > 0) {
while ($record = mysqli_fetch_array($sql)) {
?>
<tr>
<td> <?php echo $ctr++ ?> </td>
<td> <?php echo $record['TBL_PUBLISHER_CODE']; ?> </td>
<td> <?php echo $record['TBL_PUBLISHER_NAME']; ?> </td>
<td> <?php echo $record['CITY']; ?> </td>
<td id="actions">
<center>
Delete
</center>
</td>
</tr>
<!-- closing tag for php script -->
<?php
}
}
?>
<!-- -->
</table>
and below is my delete.php
if(isset($_GET['del-pub']))
{
$row = intval($_GET['del-pub']);
$sql = mysqli_query($conn,"DELETE FROM tbl_publisher WHERE TBL_PUBLISHER_CODE = $row;");
if ($sql) {
header("Location: publisher.php");
}
else {
echo "<script>alert('Publisher was not deleted.');</script>";
header("Location: publisher.php");
}
}
I want to know how to delete only the 1 row. But it keeps deleting the entire rows in the table.
After dumping the contents of $sql, I found out that my sql syntax is the culprit.
Since TBL_PUBLISHER_CODE uses char as ID. Instead of doing "="
DELETE FROM tbl_publisher WHERE TBL_PUBLISHER_CODE = $row;
I used
DELETE FROM tbl_publisher WHERE TBL_PUBLISHER_CODE LIKE '".$row."'

How to get Data from HTML Table

I am developing a project in which I have an admin and users so in the admin panel I have a table in which all videos and All User are listed With checkBox.
In the table, I have Two columns Videos and Users. In videos column, all videos are listed and in the Users column, there is another table called Select User where all users are listed with a checkbox for each video.
So the problem is when admin selects the user's checkbox I want to know for which video he selects the users so that specific video only appear to selected users in the user panel.
image link for user table
link: https://ibb.co/t25kppy
I hope you all understand my problem
I am able to the selected user's name from checkbox but don't know how to get the video for which the users are selected
<?php
require_once 'Header.php';
require_once 'Includes/DB.php';
$query = 'SELECT * FROM `videos`;';
$query2 = 'SELECT `FullName` FROM `users`;';
$result = mysqli_query($conn, $query);
$result2 = mysqli_query($conn, $query2);
$checkResult = mysqli_num_rows($result);
$checkResult2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_assoc($result2)) {
$data[] = $row2['FullName'];
?>
<main>
<div class="container">
<table class="table">
<thead>
<tr>
<th scope="col"><h4 align="center">Videos</h4></th>
<th scope="col"><h4 align="center">Users</h4></th>
</tr>
</thead>
<tbody>
<?php
if ($checkResult > 0 && $checkResult2 > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
echo '
<tr>
<form action="Select_Users.php" method="post">
<td align="center" scope="row"> <iframe width="200" height="200" src="https://www.youtube.com/embed/' . $row['youtube_video_id'] . '"frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</td>
<td>
<table class="table">
<thead>
<th scope="col"><h4 align="left">Select Users</h4></th>
</thead>
<tbody>
<tr>
<td>';
for ($i = 0; $i < count($data); $i++)
{
echo '<div><label><input type="checkbox" name="selectedUsers[]" value="' . $data[$i] . ' ">' . $data[$i] . '</label></div> <br><br>';
}
echo'
<button type="submit" name="Submit"> Submit</button>
</td>
</form>
</tr>
</tbody>
</table>
</td>';
}
}
else
{
echo 'no result fount in database';
}
?>
</tbody>
</table>
</form>
</div>
<?php
if (isset($_POST['Submit']))
{
if (!empty($_POST['selectedUsers']))
{
foreach ($_POST['selectedUsers'] as $selectedUsers)
{
echo '<h1>'.$row['youtube_video_id'].'</h1>';
echo '<h1>'.$selectedUsers.'</h1>';
}
}
else
{
echo '<h1>No value found</h1>' ;
}
}
?>
Send the video id using query parameters:
<form action="Select_Users.php?youtube_id='.$row['youtube_video_id'].'" method="post">
Then retrieve it like so:
<?php
if (isset($_POST['Submit']))
{
if (!empty($_POST['selectedUsers']))
{
foreach ($_POST['selectedUsers'] as $selectedUsers)
{
$youtube_id = $_GET['youtube_id'];
echo '<h1>'.$youtube_id.'</h1>';
echo '<h1>'.$selectedUsers.'</h1>';
}
}
else
{
echo '<h1>No value found</h1>' ;
}
}
?>
Just add a hidden input with the video id in each form, name that input so that you can read the value from $_POST, just like what you did with the users.

Delete Script Does not Delete rather it refreshes the page

I created a database where I store some pieces of data and display them on the HTML table, I put a delete button but when I run the script to delete it rather refreshes it
I don't know where it fails, and down here is my code of the table
<table class="table table-striped table-advance table-hover">
<tbody>
<?php
$conn = mysqli_connect("localhost", "blog", "0000", "blog");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($conn,"SELECT * FROM room_details ");
echo "<tr>
<th> Room Name</th>
<th> Room No.</th>
<th> Type</th>
<th> Price</th>
<th> Action</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['room_name']."</td>";
echo "<td>".$row['room_number']."</td>";
echo "<td>".$row['room_type']."</td>";
echo "<td>".$row['room_price']."</td>";
echo "<td>"?><div class="btn-group">
<a class="btn btn-danger" name="delete"
href="incl/process.php?delete=<?php echo $row['id']; ?>">DELETE<i
class="icon_close_alt2"></i></a>
</div></td>
<?php echo "</tr>";
} ?>
</tbody>
</table>
and this is delete processing code,
<?php
$conn = mysqli_connect("localhost", "blog", "0000", "blog");
if(isset($_GET['delete'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("DELETE FROM room_details WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
header("Refresh: 2; url=rooms.php");
echo '<div class="alert alert-info fade in">
<strong>SUCCESS!!</strong> Data deleted!.
</div>';
}
?>
It doesn't delete the row but now it hangs on process.php nothing is happening, where did I go wrong?
Apart from that you have to set the $id using $id = $_GET['delete']; instead of $id = $_GET['id']; because delete is what you are passing in the query string, the prepare method should be called on $conn.
Change this line:
$stmt = $mysqli->prepare("DELETE FROM room_details WHERE id = ?");
To this line:
$stmt = $conn->prepare("DELETE FROM room_details WHERE id = ?");
Not entirely sure why it's hanging, but you haven't set a variable called 'id'. Should be:
$id = $_GET['delete'];

How can I delete the selected record in mySQL from my HTML/PHP page?

My idea is to click 'Delete' link and it will pass the id to another PHP page (deleteSession.php), and then execute the query in deleteSession.php. but I couldn't seems to get the id from manageSession.php
In manageSession.php,
<table align='center' border='1' cellpadding='5' cellspacing='0'>
<tr>
<th>Session Id</th>
<th>Type</th>
<th>Date & Time</th>
<th>Venue</th>
<th>Pax</th>
<th>Delete</th>
<th>Edit</th>
</tr>
<?php
$sql = "SELECT booking_id, booking_types, dates_sessions, venue_available, room_count FROM bookings_available ORDER BY dates_sessions asc";
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
//mysqli_close($link);
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['booking_id']; ?></td>
<td><?php echo $row['booking_types']; ?></td>
<td><?php echo $row['dates_sessions']; ?></td>
<td><?php echo $row['venue_available']; ?></td>
<td><?php echo $row['room_count']; ?></td>
<td><input type="button" value="Delete"/></td>
<td><input type="button" value="Edit"/></td>
</tr>
<?php } ?>
</table>
In deleteSession.php,
<?php
include "dbFunctions.php";
include "manageSession.php";
//$sql = "SELECT booking_id, booking_types, dates_sessions, venue_available, room_count FROM bookings_available";
//$result = mysqli_query($link, $sql) or die(mysqli_error($link));
$bookingId = filter_input(INPUT_GET, 'booking_id');
$deleteQuery = "DELETE FROM bookings_available WHERE booking_id = '$bookingId'";
?>
I think in deleteSession.php file code should be as follows.
$bookingId = filter_input(INPUT_GET, 'id');
OR
$bookingId = $_GET['id'];
Because you are passing get parameter as follows.
deleteSession.php?id=
And also keep anchor as follows.
Delete
In the deleteSession.php you can try and replace:
$bookingId = filter_input(INPUT_GET, 'booking_id');
with the below code:
$bookingId = $_REQUEST['id'];
Finally at the last line you have to execute the query which is stored in $deleteQuery variable, which is not executed yet by using below code:
$qry = mysql_query("DELETE FROM bookings_available WHERE booking_id = '$bookingId'");
//will show you error if not able to delete
if(!$qry)
die("Error: ".mysql_error());
Added this at line 3 and it works:
mysqli_select_db($link ,$DB);
Because in the code I have not selected the mysql database and also the query was not executing as the first parameter $link was missing.

Categories