Can't delete a row from a Database using a img PHP - php

i was doing a backoffice for my website, and to show the data i brought a table from database to show all the upgrades requested from users, and i was thinking about putting 2 images , one for update and another for deleting that same row..
# Table from Database #
?>
<div id="DBForm">
<p id="title" align="center"> Upgrades</p>
<br/>
<?php
$resultado=mysql_query("SELECT * FROM upgrades");
if (mysql_affected_rows()>=1)
{
echo "<table class='DBTable'>";
echo "<tr>
<th>Nome</th>
<th>Upgrade</th>
<th>Morada</th>
<th>Contacto</th>
<th>NIF</th>
<th>Factura</th>
<th>Data</th>
<th>N Serie</th>
<th>Cupao</th>
<th>Alterar</th>
<th>Eliminar</th>
</tr>";
while ($linha=mysql_fetch_array($resultado))
{
echo "<tr align='center'>
<td>".$linha["nome"]."</td>
<td>".$linha["upgrade"]."</td>
<td>".$linha["morada"]."</td>
<td>".$linha["contacto"]."</td>
<td>".$linha["nif"]."</td>
<td>".$linha["factura"]."</td>
<td>".$linha["data_factura"]."</td>
<td>".$linha["n_serie"]."</td>
<td>".$linha["cupao"]."</td>
<td><img src=images/alterar.png></img> </td>
<td><img src=images/eliminar.png></img> </td>
</tr>";
}
echo "</table>";
}
?>
</div>
It was all right, but when i press the img to delete, the browser says that i sucessfully deleted the row but when i go back to the page the row is still there, what it could be ?
#Code from img to delete the row#
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "loja";
$tbl_name = "upgrades";
// Create connection
mysql_connect($servername, $username, $password)or die ("Não houve conexão");
mysql_select_db("$dbname");
$id=$_REQUEST['id'];
$sql="DELETE FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
if ($result)
{
echo "Registo apagado com sucesso!";
echo "<br>";
echo "<a href='upgrades.php'> Voltar a upgrades </a>";
}
else
{
echo "ERRO!";
mysql_close();
}
?>

Nothing is supplying this value:
$id=$_REQUEST['id'];
The page is being requested with just a link:
"<img src=images/eliminar.png>"
In order to supply the identifier you'll need to add it to the link. Maybe something like this:
"<img src=\"images/eliminar.png\">"
(or whatever the identifier is on $linha)
Additionally, please be aware that your code is wide open to SQL injection attacks. You'll want to look into using prepared statements instead of putting user input directly into SQL code.
Sidenote: You can safely remove the </img> tag; it's not a valid tag.

Related

How to delete the entire row in the database from html table instead of deleting entire table in the database

I have added delete button to the html table on each row and when clicked on delete button the entire row should be deleted but instead whole table in the database is being deleted.
here is my code for admin.php
<div class="container mt-3 ml-3">
<table class="table">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Email</th>
<th>Rating</th>
<th>Review</th>
<th>Image</th>
<th>Suggestion</th>
<th>NPS</th>
<th>Delete</th>
</tr>
</thead>
<tbody class="table-warning">
<?php
include 'database_conn.php'; // makes db connection
$sql = "SELECT feedbackID, name, email, rating, review, image, suggestion, nps
FROM feedback
ORDER BY feedbackID Desc";
$queryResult = $dbConn->query($sql);
// Check for and handle query failure
if($queryResult === false) {
echo "<p>Query failed: ".$dbConn->error."</p>\n";
exit;
}
// Otherwise fetch all the rows returned by the query one by one
else {
if ($queryResult->num_rows > 0) {
while ($rowObj = $queryResult->fetch_object()) {
echo "<tr>
<td>{$rowObj->feedbackID}</td>
<td>{$rowObj->name}</td>
<td>{$rowObj->email}</td>
<td>{$rowObj->rating}</td>
<td>{$rowObj->review}</td>
<td>{$rowObj->image}</td>
<td>{$rowObj->suggestion}</td>
<td>{$rowObj->nps}</td>
<td><a id='delete' href=delete.php?id={$rowObj->feedbackID}>Delete</a></td>
";
}
}
}
?>
</tr>
</tbody>
</table>
</div>
And here my code for delete.php. I think there is something wrong in the sql query I made.
<?php
include 'database_conn.php'; // makes db connection
$sql = "DELETE FROM feedback WHERE feedbackID=feedbackID";
if ($dbConn->query($sql) === TRUE) {
echo "Record deleted successfully. Please go to Customer Feedback Page by clicking"; echo "<a href='http://unn-w18031735.newnumyspace.co.uk/feedback/admin.php'> here</a>";
} else {
echo "Error deleting record: " . $dbConn->error;
}
$dbConn->close();
?>
This is wrong:
DELETE FROM feedback WHERE feedbackID=feedbackID
it is always true as it will be equal to itself.
What you want to use is parameters here. $_GET['id'] is where the id is.
If you use PDO, something like
$stmt = $dbConn->prepare("DELETE FROM feedback WHERE feedbackID=:feedback_id");
$stmt->execute(['feedback_id' => $_GET['id']]);
For mysqli,
$stmt = $mysqli->prepare("DELETE FROM feedback WHERE feedbackID=?");
$stmt->bind_param("i",$_GET['id']);
$stmt->execute();
this solution in delete.php has worked.
$feedbackID = $_GET["id"];
$sql = ("DELETE FROM feedback WHERE feedbackID= '$feedbackID'");

Database update fails to work within php

I have a fairly simple php page which displays a list of results from the database in a table, and the end of the row is a Dismiss button, I want to click this and have the database update to reset the flag which is original query thus dismissing the message.
I have looked at loads of examples here and have built a form around the button to call a separate php file which should execute the query to change the database and return to the original page which will be redrawn with one record less.
Everything works as expected but the database update doesn't occur.
Table drawing:
<table>
<!-- lay out the table and populate the header row -->
<tr>
<th>Site</th>
<th>Name</th>
<th>Alarm</th>
<th>Error</th>
<th>Confirm</th>
</tr>
<?php
$sql = "SELECT * FROM `hive_data` WHERE ack = 'y' "; //SQL query to find entries where the ack field is set 'y'
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)) { //start while loop to draw table one line per returned row
$line = $row["row_id"]; //define page variables from table columns
$site = $row["site"];
$module = $row["module_id"];
$alarm = $row["alarm"];
$error = $row["error"];
?>
<tr>
<!-- display each row returned listing the fields lists and a box to dismiss the alert -->
<td><?php echo $site; ?></td>
<td><?php echo $module; ?></td>
<td><?php echo $alarm; ?></td>
<td><?php echo $error; ?></td>
<td>
<form action = "data/dismiss_alerts.php" method="post">
<!-- last column of the table is a dismiss button -->
<input type="hidden" value="<?php echo $line ?>" name="line"> <!-- hidden input to send the row number to be changed -->
<input type="submit" value="Dismiss"> <!-- submit button to post data to dismiss_alerts.php -->
</form>
</td>
</tr>
<?php
} //close the while statement
?>
</table>
Dismiss alert page:
if(isset($_POST['line'])) {
$rowToUpdate = intval($_POST['line']);
$sql = "UPDATE `hive_data` SET `ack` = 'n' WHERE row_id = " . $rowToUpdate . "";
$result = mysqli_query($conn, $sql);
header('Location: ../index.php?page=home'); // return to sending page..
}
The execution refreshes the original page but the database is not updated.
Troubleshooting dismiss alert page:
if(isset($_POST['line'])) {
$rowToUpdate = intval($_POST['line']);
$sql = "UPDATE `hive_data` SET `ack` = 'n' WHERE row_id = " . $rowToUpdate . "";
echo $sql;
if($conn->connect_error) {
echo "Connection failed";
} else {
echo "Connected";
if($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
The first if clause works fine so I stay on the dismiss alerts page and get the echo of my query and a message saying the database is connected but the second if clause never reports anything.
UPDATE `hive_data` SET `ack` = 'n' WHERE row_id = 253Connected
I have tested the query inline on the calling page so that it actually deletes the last line of the table on every refresh so I am pretty sure that bit works, but I am really stumped with this.
Any ideas?
OK so after spending all morning on this ten minutes after posting here I found that despite my troubleshooting line above the db was not connected I had to build a connect and disconnect into the page and it works fine.
Now to read up on prepared statements and re-do it all that way :-)

Add table row for each table row in database table

I couldn't really find another post about this problem.
I am trying to add in html a new table row for every new table row I have in phpmyadmin table with php script.
My code is:
<?php
if($check == true)
{
echo" <a href='php/logout.php' class='subpages'>Logout</a>
<tr>
<td>
FileName: <a href='../uploads/$filename'>$filename</a>
</td>
<td>";
$connect = mysql_connect("localhost","root","");
mysql_select_db("phplogin"); // select DB
$getcomment = mysql_query("SELECT comment FROM files WHERE name='$filename'");
while($row = mysql_fetch_assoc($getcomment))
{
echo"Comment: ".$row['comment']." </td>
</tr>";
}
}
?>
The check at the begging checks if a file is actualy uploaded if it is a connection is made to get the name of the file and the comment attached to it.
Then finaly when the info has been taken I want to make a table row and 2 colusm for FileName and Comment. The result of my code replaces the already created row with a new one.
Is there a way to create a new row for each new File and Comment that has been taken with PHP script only ?
Try this... please let us know is it working or not...
if($check == true)
{
echo" <a href='php/logout.php' class='subpages'>Logout</a>
<table><tbody><tr>
<th>File Name</th>
<th>Comments</th>
</tr>
<tr>
<td>
FileName: <a href='../uploads/$filename'>$filename</a>
</td>
</tr>
";
$connect = mysql_connect("localhost","root","");
mysql_select_db("phplogin"); // select DB
$getcomment = mysql_query("SELECT comment FROM files WHERE name='$filename'",$connect);
$res = mysql_fetch_row($getcomment);
$num_rows = mysql_num_rows($getcomment);
if ($num_row > 0){
for ($i=0;$i<$num_row;$i++){
echo "<tr><td><Comment: ".$res[$i]."</td></tr>";
}
}
}

How to update a field in sql table with inputs from an html form against displayed results which are themselves output of an sql query?

I have a database that looks like below.
Id Class Name Email Comments
1 4 Thomas Sheffield tom#email.com
2 5 Natasha Rosewhite natasha#email.com
3 4 Jerome Manyville jerry#email.com
4 6 Susan Carrey suzzy#email.com
5 4 Selina Waterwall selina#email.com
I have a php page that would query names from a particular class and display it as an html table.
The html page would also have an input field against each displayed name where the comments can be entered. After the submit button is hit, the comments against each specific name should be updated in the database.
I have applied the following logic - the Id which is unique will be carried over to another php page (that is indicated by the action field of the submit button) and then use $_POST to update the comments.
I have used the following code
<?php
session_start();
$username = "Debo";
$password = "123456";
$hostname = "localhost";
$Idtemp = array();
$i=0;
$sql = "SELECT `Id`, `Name`, `Email` FROM `registration` WHERE `Class`=4";
$dbconnect=mysqli_connect($hostname, $username, $password, "test1")
or die("unable to connect");
$result = mysqli_query($dbconnect, $sql);
ECHO "<table border=\"2\">
<tr bgcolor=\"#cccccc\">
<td width=\"100\">Id</td>
<td width=\"200\">Name</td>
<td width=\"100\">Email</td>
<td align=\"center\" width=\"100\">COMMENTS</td>
</tr>";
while($row = mysqli_fetch_array($result))
{ ECHO "<tr><td width=\"100\">".$row['Id']."</td>";
ECHO "<td width=\"200\">".$row['Name']."</td>";
ECHO "<td width=\"100\">".$row['Email']."</td>";
ECHO "<td align=\"center\"><input type=\"text\" name=\"comments[]\" size=\"50\"</td></tr>";
$IDtemp[$i]=$row['Id'];
$i++;};
ECHO"
<table>
<form action=\"processregistration.php\" method=\"post\">
<tr>
<td colspan=\"8\" align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Submit Feedback\"></td>
</tr>
</table>";
$_SESSION['CURRENTID']=$IDtemp;
?>
And then on submit, it goes to
<?php
session_start();
$COMMENTS = array();
$ID = $_SESSION['CURRENTID'];
var_dump($ID);
if (isset($_POST['submit']))
{
$COMMENTS=$_POST['comments'];
};
$username = "Debo";
$password = "123456";
$hostname = "localhost";
foreach($ID as $key=>$n)
{
$sql = "UPDATE `test1`.`registration` SET `Comments` = $COMMENTS[$key] WHERE `registration`.`UID` = $n";
var_dump($sql);
$dbconnect=mysqli_connect($hostname, $username, $password, "test1")
or die("unable to connect");
mysqli_query($dbconnect, $sql);
if (mysqli_error($dbconnect))
{
ECHO "Error Description:".mysqli_error($dbconnect);};
};
?>
I find that the 'comments' are not getting posted.
I get the notice 'undefined index: comments' on line 10.
What am I doing wrong?
I am pretty new to php. Please help. Also, the way through which I am trying to achieve what I intend to get, is that correct or is there a better approach?
Regards.
It looks like your comments[] inputs are not inside your <form>. Moving the opening form tag to the beginning of your HTML should fix the undefined index notice:
ECHO "<form action=\"processregistration.php\" method=\"post\">
<table border=\"2\">
...

How do I get only ONE link to change dynamically using PHP?

Sorry, I'm not sure how to really word my question. Here it goes.
If you go to my page http://www.eveo.org/stack/view.php you will notice on the right hand side there are links that read "restore" and "delete". If it says restore, the value for the "deleted" table in the database is "y".
The problem: When I click on a link, all of them change, not just the one. What I need to do is when I click on "delete" or "restore" on any of them, only that row will delete and restore and only will that rows link update, with all the others staying the same. The value in the database has to change from "y" to "n" or vice versa depending on the link.
The code that currently changes my link for all of them is:
echo "<td><a href='view.php?'>";
$y="$row[deleted]";
$x="$row[id]";
if ($y == 'n'){
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$row[id]'");
echo "delete";
}
else if ($y == 'y'){
mysql_query("UPDATE inventory SET deleted = 'n' WHERE id='$row[id]'");
echo "restore";
}
echo"</a></td>";
I've been trying to solve this for hours, and it's not working.
Requirements: It has to use URL rewriting, so I can't do this change thing with javascript or something, personally I would have, but these are my professors requirements.
Source code:
VIEW.PHP
<?php { ?>
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETE</th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// while($r = mysql_fetch_array($resultDeleted))
// {
// echo $r[0];
// }
?>
<?php while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>$row[id]</td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td><a href='view.php?'>";
$y=$row[deleted];
$x=$row[id];
if ($y == 'n'){
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$row[id]'");
echo "delete";
}
else if ($y == 'y'){
mysql_query("UPDATE inventory SET deleted = 'n' WHERE id='$row[id]'");
echo "restore";
}
echo"</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
<?php } ?>
It looks like you are trying to get a $_GET variable using the code:
$y="$row[deleted]";
$x="$row[id]";
This is never going to work. First of all you don't need to add double quotes around your variables. Second the correct syntax for getting the $_GET variables is:
$delete = $_GET['delete'];
$id = $_GET['id'];
As you can see I have given your variable names better descriptive names.
Second, when you are just adding those variables to a query you will have a huge SQL injection hole in your application:
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$id'");
What if I was a hacker I would add an id of: 1' or 1=1, which would result in the following query:
UPDATE inventory SET deleted = 'y' WHERE id='1' OR 1=1
And suddenly I set the deleted status of all records in the table. I could even get into others tables using this attack in do whatever I want.
So you should always use mysql_real_escape_string():
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$id'");
So what you will get is the following:
$delete = mysql_real_escape_string($_GET['delete']);
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE inventory SET deleted = '$delete' WHERE id='$id'");
Another thing is that you don't need to keep opening and closing the PHP tags. Only if you want to add some HTML.
Next:
instead of echoing all that stuff simply use HEREDOC:
So instead of doing:
echo "<tr>";
echo "<td>$row[id]</td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td><a href='view.php?'>";
You can simply do:
echo <<<HTML
<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
etc
FOOBAR;
As you can see it need quotes to get an array element.
After that you should build your links:
$delete = 'n';
if ($row['deleted'] == 'n') {
$delete = 'y';
}
echo 'delete';
As a general note:
ALWAYS ENABLE FULL ERROR REPORTING ON DEV ENVIRONMENT so you can see what the f*&k is going on / wrong. So place this at the top of your scripts:
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
What you want will not work like that. Your code changes your database entries upon each refresh. To illustrate, if you will keep refreshing your page, the links will change from deleted to restored and vice versa indefinitely.
What you need to do is take those two update clausules out of the loop, give each link an id. Something along the lines of
if ($y == 'n'){
echo "<a href='view.php?link_id=$row[id]&case=delete'>delete</a>";
}
else if ($y == 'y'){
echo "<a href='view.php?link_id=$row[id]&case=restore'>restore</a>";
}
Then somewhere above the loop you would to the actual update.
if(!empty($_GET['link_id'])) {
if($_GET['case'] == 'restore') {
// udpate
} else {
// update
}
}
The other way would be to use a form for this. Then you would just catch the post request and do the same thing.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// do stuff
}
or
if(!empty($_POST)) {
// do stuff
}
You need to pass the id to the query, maybe something like this:
<?php while($row = mysql_fetch_array($result)) {
if($row['deleted']=='y'){$status='restore';}else{$status='delete';}
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['manufac']}</td>";
...
echo "<td><a href='view.php?id={$row['id']}&do=$status'>".ucfirst($status)."</a></td>";
echo "</tr>";
?>
Then have the script receive a request to alter the values, something like this would go at the top of your script:
<?php
if(isset($_GET['id']) && is_numeric($_GET['id']) && isset($_GET['do'])){
$set=null;
$id=(int)$_GET['id'];
if($_GET['do']=='delete'){$set='n';}
if($_GET['do']=='restore'){$set='y';}
if($set != null){
mysql_query("UPDATE inventory SET deleted = '$set' WHERE id='$id'");
}
}
?>

Categories