delete row php&mysql dynamique link - php

I want to make a link to delete a record from database using dynamic links with php however i couldn't figure it out
this is my code :
<?php
$query = "SELECT * FROM posts ";
$result = mysqli_query($connect, $query);
?>
<table>
<tr style="background: #afafaf;">
<th>Id</th>
<th>Title</th>
<th>Action</th>
</tr>
<?php
while($rows = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td class=\"center\">".$rows['id']."</td>";
echo "<td>".$rows['title']."</td>";
echo "<td> delete</td>";
echo "</tr>";
}
?>
</table>
the output link would be like .../delete.php?id=X
can anyone help me write the code for delete.php ?

Have the below code in your page. This first checks if $_GET['id'] is set. It will only run if it is, that way you don't get Undefined Index error.
<?php
if (isset($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
I also used htmlspecialchars to sanitize the user input. You could run some validation using ctype_digit to ensure that the input is actually an integer.
I suggest using prepared statement in MySQLi to prevent SQL injection.
Edit 1
Example with ctype_digit. This checks if the id is set and if it is a number, technically you could just use ctype_digit because if id is empty then ctype will return false as var_dump(ctype_digit("")); will return false, with that logic in mind, the value must be set for ctype_digit to work and it must be an integer.
<?php
if (ctype_digit($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>

That would be something like this:
$deleteId = $_GET['id'];
$sql = "DELETE FROM posts WHERE id = ".$deleteId;
Remember to escape your variables before sending them off to the MySQL server.

Related

php a href display data from mysql database and link it to a new page

I have a php & mysql search script which is working, after result displayed users can click below link and it will open a new page and display more mysql info, i am stuck with linking the ahref link ($field2name) to the new page (getprofile.php).
Now the problem is getprofile.php showed nothing and displayed 0 results, however i tried to put static data in getprofile.php it is working properly and can show profile data from mysql, can anyone enlighten me what is missing?
from search page user can click this link:
<td><a href="getprofile.php?'.$field2name.'" target = "_blank">'.$field2name.'</td>
getprofile.php:
<?php
$conn = mysqli_connect("localhost","root","password","demo");
$pkey = mysql_real_escape_string($_GET[$field2name]);
// $pkey = "4027500001"; <-------if i put static data it can show profile data
$query = "SELECT * FROM nhc WHERE code =" . $pkey;
$result = $conn->query($query);
if ($result->num_rows > 0) {
echo "<table border='1'><tr><th>code</th><th>Name</th><th>class</th><th>AM</th><th>May GA</th><th>June GA</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["code"]."</td> <td>".$row["name"]."</td> <td> ".$row["class"]."</td> <td>".$row["am"]."</td> <td>".$row["may"]."</td><td>".$row["june"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
You are not assigning $field2name in any variable. Moreover your quotes are mismatching and are not forming a well formatted url
<td><a href="getprofile.php?value=<?=$field2name?>" target = "_blank">'<?=$field2name?></td>
now to get the value
use $_GET['value']
You need to give the GET parameter a name so that you can access it in PHP:
<td><a href="getprofile.php?code='.$field2name.'" target = "_blank">'.$field2name.'</td>
then in PHP:
$pkey = mysql_real_escape_string($_GET['code']);
Note that you should use prepared statements to protect yourself from SQL injection; mysql_real_escape_string is not sufficient (see this Q&A). For example:
$query = "SELECT * FROM nhc WHERE code = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_GET['code']);
$stmt->execute();
$result = $stmt->get_result();

Php if and else

I'm trying to make this code work but I don't know why it won't. Basically I want it to display a name if the nickname column in the database is null. And if it's not null it should display the nickname. Also I'm somewhat noob so keep that in mind when responding.
$namn = mysql_query("SELECT name FROM Horseinfo WHERE name = '$somevariable'");
$nicknamn = mysql_query("SELECT nickname FROM Horseinfo WHERE name = '$somevariable'");
<? $row = mysql_fetch_array($nicknamn,$namn);
if(is_null($nicknamn)) {?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo $row['name'];?></div>
<?} else {?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo $row['nickname'];?></div>
<?}?>
Based on assumption I would say that your nickname column does not contain a database NULL value, rather it would be an empty string instead (this totally depends on the routine filling the Horseinfo table). You also only need one SQL query to fetch both name and nickname.
My suggestion would be to use empty() instead:
// try to use mysqli_* instead of mysql_* functions, mysqli_query() expects parameter 1 to be a database connection resource
$res = mysqli_query($connection, "SELECT name, nickname FROM Horseinfo WHERE name = '$somevariable'");
if ($res && mysqli_num_rows($res)>0) {
$row = mysqli_fetch_row($res);
$horseName= empty($row['nickname']) ? $row['name'] : $row['nickname'];
?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo horseName;?></div>
<?php } ?>

Updating a single record Via ID = ID

I've ran into a wall at the moment, This code brings up a table with a button on the end of each record. Once pressed this then does a function to UPDATE the Health record by -5.
This works great for the job but it effects all rows, I've tried to get it to only touched one record via the ID but no luck! if you can help that would be great!
the php
$sql="SELECT `id` , `FirstName` , `Health` FROM ajax_demo WHERE `id` = `id` LIMIT 0 , 30";
$result = mysql_query($sql);
if(isset($_REQUEST['submit']))
{
counterminus();
}
function counterminus()
{
$cmeter = $cmeter - 1;
$id = $_POST["id"];
$FirstName = $_POST["FirstName"];
mysql_query("UPDATE ajax_demo SET `Health` = `Health` - `Damage` WHERE id = {$id}");
Header("location:oo_test.php");
}
This is the php / form
<?php
echo
"<table border='1'>
<tr>
<th>id</th>
<th>Firstname</th>
<th>health</th>
</tr>";
while($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach($row as $cell) {
echo "\n<td>$cell</td>";
}
echo '<td><form id="theForm" action="" method="POST" >
<input type="submit" name="submit" id="submit" value="Attack" />
<input type="hidden" name="'.$row[1].'" /></form></td></tr>';
echo "\n\n";
}?>
This is vunerable to attack through the $_POST['id'] variable. Use mysql_real_escape_string, or better, prepared queries through PDO or MySQLi, anyway this is orthogonal to the issue you are having, it's just a good idea to be aware of it.
You're never actually submitting a HTML form field with the name id. In addition, in your HTML, $row will be NULL outside of your while loop, so will be undefined in the first place. This will mean that the name of your hidden field will be blank, and that your SQL is saying UPDATE WHERE id=, which is invalid and will cause an error.
To fix, you need to submit a form field with the name "id" such that $_POST['id'] actually contains a value.
Why did you write {id} instead of $id ?
Plus your code is totally unsafe and could be easily altered and hacked.
You should try PDO instead of mysql_query which is also depreciated.
http://php.net/PDO

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'");
}
}
?>

PHP - $GET and delete from MySQL

I have an a href which looks like that: Delete
And file delete-news.php is as follow:
<?php
if(isset($_GET["?deleteID='.$id."]))
{
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
But it is returning GET NOT SET. What I'm doing wrong?
Use this, and for god's sake escape your inputs.
if(isset($_GET['deleteID'])) {
$result = mysql_query("DELETE FROM `news` WHERE id='".mysql_real_escape_string($_GET['deleteID']). "'");
echo mysql_error();
if($result)
echo "succces";
} else {
echo 'GET NOT SET';
}
$_GET will have each element of the GET variables already broken down, so no need to include the URL data. So, in your example, the link ?deleteID=123 would produce $_GET['deleteID'].
Try using that, but also remember to sanitize the values you receive in from URLs. If it's going to be a numeric value, I suggest casting it:
$deleteID = (int)$_GET['deleteID'];
Please also note that changes to the system should only happen via POST, and never GET. Otherwise (for example), you might get a spidering bot that deletes your whole site. See this post for more references:
https://stackoverflow.com/questions/679013/get-vs-post-best-practices
You need to check $_GET for just deleteID. Later, reference it as $_GET['deleteID']. Also, call mysql_real_escape_string() on $_GET['deleteID'] to retrieve your query parameter $id.
if(isset($_GET["deleteID"]))
{
$id = mysql_real_escape_string($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
Try this instead:
<?php
if(isset($_GET['deleteID']))
{
$id = intval($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result) echo "succces";
} else {
echo "GET NOT SET";
}
?>
Note that I'm making the given deleteID into an int, meaning that values other than some form of number will become 0.
Also, you can't wrap a table- and/or column name with ' - backticks are the way to go!
<?php
if(isset($_GET["deleteID"]))
{
$id = ($_GET['deleteID']);
$result = mysql_query("DELETE FROM news WHERE id='".mysql_real_escape_string($id)."'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
is correct one
You obtain GET NO SET, because the $_GET associative array does not contain ?deleteID='.$id.
In order for you to obtain the id, you need to so something like this:
$id = $_GET['deleteID'];
Also
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
That is very unsafe as it allows SQL injections. Instead, do:
$query = sprintf("DELETE * FROM news WHERE id=%d",
mysql_real_escape_string($id),
$result = mysql_query($query);
I hope this helped.

Categories