PHP Not deleting MYSQL Database row - php

I've spent a lot of time messing around with PHP and MYSQL and I've finally managed to create a "to do list" sort of thing that allows the user to submit a "to do" task and for it to add it to a database and then show it. I've followed many tutorials as I've tried to teach myself PHP blah blah. But for some reason i cannot get the delete script working.
echo "<td><a href='delete.php?=Delete" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
Above is the code for the delete button
Here is the delete script apologies for the many commented out lines I've tried many 'solutions'.
$ID = $_GET['task_id'];
//$delete_query = "DELETE FROM Tasks WHERE ID = $ID" ;
$sql = "DELETE FROM Tasks WHERE task_id = $ID;";
echo $row['task_id'];
// $delete_query = "DELETE FROM Tasks WHERE task_id = ['task_id'] ";
/* if(isset($GET['task_id'])){
$delete = $_GET['task_id'];
mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '$delete'");
} */
echo("Succesfully deleted");
mysqli_close($link);
The script runs and it says "successfully deleted" but the entry still shows. In the F12 Menu/Network tab I get this
error
And when I click "view source" it shows the ID of the row. I can't seem to figure out what is wrong.

I am try to delete data using php pdo. and data can deleted successfully so you can try this code.
I have created 2 file. first req.php and second delete.php.
Here req.php file can fetch data and delete.php file can delete this data from send req.php file id.
req.php
<?php
require "connection.php";
//This is a fetch data from database
$sql = "SELECT * FROM test";
$select = $conn->prepare($sql);
$select->execute();
?>
<html>
<head>
<title>Data</title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
while($data = $select->fetch())
{
?>
<tr>
<td><?php echo $data['id']; ?></td>
<td><?php echo $data['student_name']; ?></td>
<td><?php echo $data['email_address']; ?></td>
<td><button onclick="return conformation();">Delete</button></td> <!-- This is a delete data button --->
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
<script>
//This is a conformation function if it will return true then data can delete otherwise data cannot deleted.
function conformation() {
let conform = confirm("Can you delete this data ?");
if (conform == true) {
return true;
} else {
return false;
}
}
</script>
delete.php
<?php
require "connection.php";
if(isset($_GET['id']))
{
$sql = "DELETE FROM test WHERE id = ?";
$deleteData = $conn->prepare($sql);
if ($deleteData->execute([$_GET['id']]))
{
header('location: http://local.test/req.php');
}
}
?>

The first issue is trying to get task_id from REQUEST params while you sending "Delete" key.
The second is you passed the task_id to db as a string, while I think it's an Integer type in the database.
So you have to do that:
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
$task_id = mysqli_real_escape_string($connect, $_GET['task_id']);
if (!empty($task_id)) {
$delete_query = mysqli_query($connect, 'DELETE FROM Tasks WHERE task_id = '.$task_id);
if ($delete_query) {
echo 'deleted successfully';
} else {
echo("Error: " . mysqli_error($connect));
}
} else {
echo 'task_id is empty !';
}

You can solve this or debug it by doing the following.
parse the right URL parameter
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
this will send a task_id value to the delete page.
checking and logging the response of my SQL in delete.php
if(isset($_REQUEST['task_id'])){
//escape to avoid SQL injection
$delete = mysqli_real_escape_string($connect, $_REQUEST['task_id']);
$process = mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '".$delete."'");
if($process){
echo("Succesfully deleted");
}else{
echo("Error description: " . mysqli_error($connect));
}
}else{
echo("no id supplied");
}
in your question, you also had this: $GET['task_id'], which I believe was null.

Related

Calling two methods from table wrapper in a class

I want to create a table which generates data from the database and I need to have update and delete function for each row of data in the table. But i failed to do both update and delete because i put both function in one controller
This is my view file which include the controller to show the data.
<table class="table table-hover">
<tr class="table-active">
<td>Booth ID</td>
<td>Booth Location</td>
<td>Participant ID </td>
<td></td>
<td></td>
</tr>
<tr>
<?php include 'BoothViewController.php'; ?>
</tr>
</table>
This is my controller to display the data in rows. Each row will have update and delete function. The update function will bring the user to another page while delete function is merely remove that row of data.
<?php
require 'boothmodel.php';
$result = viewbooth();
if($result){
while($array = mysqli_fetch_array($result)){
echo "<td>".$array["BoothID"]."</td>";
echo "<td>".$array["Boothlocation"]."</td>";
echo "<td>".$array["ParticipantID"]."</td>";
echo "<td><a href='BoothFormUpdate.php?bid=".$array['BoothID'].
"&blocation=".$array['Boothlocation']."&pid=".$array['ParticipantID']."'>Update</a></td>";
echo "<td><a href='BoothViewController.php?bid=".$array['BoothID'].
"&blocation=".$array['Boothlocation']."&pid=".$array['ParticipantID']."'>Delete</a></td>";
}
return;
}
if(isset($_GET['bid'])){
$selectedbid = $_GET['bid'];
$result = deletebooth($selectedbid);
if($result){
echo "<script language = 'javascript'>";
echo "alert('Booth deleted!');";
echo "window.location.href = 'BoothView.php';";
echo "</script>";
}
}?>
this is my model.
<?php
require 'connection.php';
mysqli_select_db($conn, "ims");
function viewbooth(){
global $conn;
$query = "SELECT * FROM booth";
$result = mysqli_query($conn, $query);
return $result;
}
function updatebooth($bid, $newbloc){
global $conn;
$update = "UPDATE booth
SET Boothlocation='".$newbloc.
"'WHERE BoothID='".$bid."'";
$result = mysqli_query($conn, $update);
return $result;
}
function deletebooth($selectedbid){
global $conn;
$delete = "DELETE FROM booth WHERE BoothID=".$selectedbid;
$result = mysqli_query($conn, $delete);
return $result;
}?>
I know i can simply do the delete function in another controller but im trying to put all in one controller.
You need to create a basic routing mechanism, e.g.
if(isset($_GET['bid'], $_GET['action']))
{
$selectedbid = $_GET['bid'];
$action = $_GET['action'];
switch ($action)
{
case 'delete':
$result = deletebooth($selectedbid);
if($result){
echo "<script language = 'javascript'>";
echo "alert('Booth deleted!');";
echo "window.location.href = 'BoothView.php';";
echo "</script>";
}
break;
case 'update':
// do the updating
break;
}
}
then you can add update and delete links to your items:
Update item
Delete item
Your code hardly resembles the MVC pattern and has many issues. However, the routing idea should work.

Add 'delete' button to php results table

I outputted the results of a MySQL table to an HTML table, I'm trying to add a Delete button to remove the user but it doesn't work.
HTML form code:
<?php
$response = $bdd->query('SELECT * FROM users');
$i = 1;
while ($datas = $response->fetch()) {
?>
<tr>
<td><?php echo $datas['first_name']; ?></td>
<td><?php echo $datas['last_name']; ?></td>
<td>
<form action="_delete.php?id=<?php echo $datas['id']; ?>" method="post">
<input type="hidden" name="name" value="<?php echo $datas['id'];?>">
<input class="btn btn-danger" type="submit" name="submit" value="X">
</form>
</td>
</tr>
And this is my _delete.php :
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'root', 'root');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
?>
<?php
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
//sends the query
mysql_query ($query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
?>
My result url is good /_delete.php?id=13 but Delete script isn't.
I have this error: Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future
Any idea?
Your messing around with GET and POST params. You defined a get param named id containing your id and a post param named name containing also your id.
But currently you are trying to access the get param with $_POST (which contains only post params).
To solve your problem, you should use $_GET['id'] or $_POST['name'].
In each way, keep in mind to protect you input from sql injections. Currently the user could pass anything else as well. A simple cast to an int, would be enough.
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
I have incoporated a few suggestions in my answer, try and see if it works.
Create a connection, then get the ID using $_GET instead of $_POST.
<?php
$con=mysqli_connect("localhost","dbuser","dbpassword","dbname");
if($con==false){
die("ERROR:Could not connect.". mysqli_connect_error());
}
else{
$id=$_GET['id']
$query = "DELETE FROM users WHERE id='$id' LIMIT 1";
//sends the query
mysql_query ($con,$query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
}
?>

Trying to Delete the data displayed in my tables

I have been able to display the data from my database on to my website and I'm trying to delete a single row.
Now the button works but it completely deletes everything as you may tell from the code.
I have no idea on how to assign the delete button to a specific row in my table, where it just deletes that data in that specific row.
On top of this I have one delete button that sits upon my table and have no clue on how to set separate delete buttons for each row given.
admin.php (Displaying my data)
<?php
echo "<table style='box'>";
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Role</th>
<th>Email</th><th>Username</th><th>Delete</th><th>Amend</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='box'>" . parent::current(). "</td>";
}
function beginChildren(){
echo "<tr>";
}
function endChildren(){
echo "</tr>";
}
}
require 'connection.php';
try {
$stmt = $conn->prepare("SELECT id, FirstName, LastName, Role, Email, Username FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v){
echo $v;
}
}
catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="post" action="delete.php">
<input <input class="btn-default" type="submit" name="login" value="Delete">
</form>
<?php
echo "</table>";
?>
delete.php
<?php
$servername = 'localhost';
$username = 'root';
$pass = 'root';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//sql to delete record.
$sql = "DELETE FROM users WHERE id = id";
$conn->exec($sql);
echo "Record deleted!";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I would show an image but I don't have enough reputation points to display it.
The WHERE clause in your DELETE statement will always return to true. On every row, ID will always equal ID. Hence, everything is deleted. You need to pass a parameter to delete script to filter on the row you want deleted. You can do so by a hidden HTML input value using get="method" of <form>.
However, the key is how to obtain that id from webpage's select query. Additionally, you will want to put the input button at the end of each row to delete the corresponding row's id. For these two items, you might have to return to traditional loop onto web page instead of the RecursiveArrayIterator() because we need to add a non fetched object (form delete button) into table.
admin.php (notice form button as last table cell of each row)
...same code as above...
try {
$stmt = $conn->prepare("SELECT id, FirstName, LastName, Role, Email, Username FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $result->fetch()) {
?>
<tr>
<td style="box"> <?php echo $row['id']; ?></td>
<td style="box"> <?php echo $row['FirstName']; ?></td>
<td style="box"> <?php echo $row['LastName']; ?></td>
<td style="box"> <?php echo $row['Role']; ?></td>
<td style="box"> <?php echo $row['Email']; ?></td>
<td style="box"> <?php echo $row['Username']; ?></td>
<td>
<form method="get" action="delete.php">
<input type="hidden" name="rowid" value="<?php echo $row['id']; ?>">
<input class="btn-default" type="submit" name="login" value="Delete">
</form>
</td>
<tr>
<?php
}
}
catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
delete.php (notice $id generated from $GET() and used in delete query)
$servername = 'localhost';
$username = 'root';
$pass = 'root';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// OBTAIN ROWID FROM $_GET
if(isset($_GET['rowid'])) {
$id = $_GET['rowid'];
}
// DELETE SPECIFIED ROW
$sql = "DELETE FROM users WHERE id = ".$id;
$conn->exec($sql);
echo "Record deleted!";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Trying to follow what you have. Have you tried setting the id to a var before doing?
$sql = "DELETE FROM users WHERE id = id";
Example:
$sql = "DELETE FROM users WHERE id = '$id'";
One problem is that your DELETE statement does not include a variable.
//sql to delete record.
$sql = "DELETE FROM users WHERE id = id";
You need something more like:
//sql to delete record.
$sql = "DELETE FROM users WHERE id = " . $id;
where $id is defined with the ID of the selected row.
Let's address another "hidden" problem.
Now the button works but it completely deletes everything as you may tell from the code.
Given the fact that you said this deletes ALL the records, I would guess that the id of each of your rows is the string 'id' and not a unique integer value.
DELETE FROM {table} WHERE id = {number} does not delete ALL records. It only deletes records matching the condition. You should make sure that you are setting id's correctly when adding rows. The id column should have the following properties: INT UNSIGNED NOT NULL AUTO_INCREMENT.

DELETE record in a row in PHP

I was trying to delete a record on my Database. So basically I created a table that contains all of my records. Now what I need to do is when I click on the "DELETE" link it would delete the record selected row.
Here's what it looks like:
So basically I have 3 pages here.
1. page.php
2. add.php
3. delete.php
Here's my page.php file:
<table border="1">
<thead>
<th>email</th>
<th>date</th>
<th>delete</th>
</thead>
<tbody>
<tr>
<?php
foreach($emails as $mail){ ?>
<td><?php echo $mail['email']; ?></td>
<td><?php echo $mail['date']; ?></td>
<td><?php echo "<a href='delete.php?id=". $mail['id']. "'>DELETE</a>"; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Here's my add.php file:
<?php
require("new-connection.php");
session_start();
$email = $_POST['email'];
if(empty($_POST['email']) AND (filter_var($email, FILTER_VALIDATE_EMAIL) === false))
{
$_SESSION['message'] = "email cannot be blank";
}else{
$query = "INSERT INTO email_tbl (email, date)
VALUES('$email', NOW())";
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "New RECORD has been added correctly!";
}
else
{
$_SESSION['message'] .= "Failed to add new Interest";
}
}
header('Location: email.php');
?>
Here's my delete.php file so far:
<?php
require("new-connection.php");
session_start();
$query = "DELETE FROM email_tbl
WHERE id={id} LIMIT 1";
$deleteEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "RECORD has been DELETED correctly!";
}
else
{
$_SESSION['message'] .= "Failed to DELETE RECORD";
}
header('Location: email.php');
?>
So now when I click the delete link it must delete the button real time. Any idea?
Modify your delete.php to retrieve the url parameter:
<?php
require("new-connection.php");
session_start();
$id = $_GET['id'];
$query = "DELETE FROM email_tbl
WHERE id='$id' LIMIT 1";
$deleteEmail = run_mysql_query($query);
if($deleteEmail)
{
$_SESSION['message'] .= "RECORD has been DELETED correctly!";
}
else
{
$_SESSION['message'] .= "Failed to DELETE RECORD";
}
header('Location: email.php');
?>
As for your add.php, you are using this:
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
You should change it to this:
$insertEmail = run_mysql_query($query);
if($insertEmail)
What you are doing right now is you are executing the query twice by calling run_mysql_query twice. This should fix it
Sense when what run_mysql_query a function in php?
http://php.net/manual-lookup.php?pattern=run_mysql_query&scope=quickref
Update the delete.php file:
$id = $_GET['id'];
$query = "DELETE FROM email_tbl WHERE id='$id' LIMIT 1";
and also check the section below:
You are running the query twice. so it is obvious it will add the same record twice.
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "New RECORD has been added correctly!";
}
Modify you code to use the run_mysql_query once only.
$query = "DELETE FROM email_tbl WHERE id=".$_GET['id']." LIMIT 1";

Execute query update with form from a query

I am trying to create a button on my user list page to delete that row, or make that user an admin.
Here is the info for the user query and html:
<?php
$query = "SELECT * FROM users";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
$rows = $stmt->fetchAll();
?>
<?php foreach($rows as $row) : ?>
<?php
if($row['usertype'] == 2) {
$usertype = "<span style='color:#F7FE2E;'>Donator</span>";
} elseif($row['usertype'] == 3) {
$usertype = "<span style='color:red;'>Admin</span>";
} elseif($row['usertype'] == 4) {
$usertype = "<span style='color:orange;'>Owner</span>";
} else {
$usertype = "<span style='color:#585858;'>Normal</span>";
}
?>
<tr>
<!--<td><?php echo $row['id']; ?></td>-->
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8');?></td>
<!--<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8');?></td>-->
<td><?php echo htmlentities($row['steamid'], ENT_QUOTES, 'UTF-8');?></td>
<td><?php echo $usertype?></td>
<td><form action="" method="post">
<input type="submit" name="admin" value="Promote" />
</form></td>
</tr>
<?php endforeach; ?>
And the code where I prepare and execute my update query:
if(!empty($_POST['admin']))
{
$query = "UPDATE `users` SET `usertype` = '3' WHERE `id` = " . $row['id'];
// $query_params = array(':id' => $row['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
}
Unfortunately I when I run this current setup, it updates the very last row. To further ask what I am looking for, is I have a list of users:
where "admin_b" is a button that forced $_POST['admin']
Billy admin_b
Bob admin_b
Jill admin_b
Jack admin_b
UPDATE:
So in my form I have an input with <input type="hidden" name="id" value="<?php $row['id']; ?>" /> and added this to my SQL $query = "UPDATE users SET usertype = '3' WHERE id = :id"; $query_params = array(':id' => $_POST['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
send an id with $_POST request, now you are always update user with id = $row['id']
WHERE `id` = " . $row['id'];
row[id]edit?=edit.php= ...
and let's say you have list all the members and beside them is an href, the code above will execute, it will display let's say Billy?edit.php=1, wherein 1 is his primary key, then for the next, when you scroll the cursor to the next href of the next user, Jim, it will display, Jim?edit.php=2, in your edit.php,
if(isset($_POST['edit])){
code goes here to make the user an admin..
You can also make an href for the delete, similar to this edit..
This is just an idea/hint that I can give to you, but your problem can be solved in many different ways, it just depends on your approach on how you could do it :D goodluck.

Categories