How to Remove a Database Entry when a Link is Clicked - php

I wanted to expand my PHP skills so I read through a tutorial on tutorialzine. I understand the instructions presented in the tutorial. But when it comes to expanding on it I seem to be lacking a connection. My main goal was to simply delete a selected note when an a tag is clicked. However I don't know how to select the id assigned to the note to be able to pass it to my delete function.
Source: http://tutorialzine.com/2010/01/sticky-notes-ajax-php-jquery/
Thanks for the help.
<?php
error_reporting(E_ALL^E_NOTICE);
require 'connect.php';
mysql_query("DELETE FROM notes WHERE id>3 AND dt<SUBTIME(NOW(),'0 1:0:0')");
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
$notes = '';
$left='';
$top='';
$zindex='';
while($row=mysql_fetch_assoc($query)){
list($left,$top,$zindex) = explode('x',$row['xyz']);
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" href="javascript:;" onclick="deleteNote('<? echo $row['id']; ?>');"> </a>
</div>';
}
function deleteNote(id){
$sql="DELETE FROM notes WHERE id='$rows['id']'";
$result=mysql_query($sql) or die("Error when tryin to delete note.");
}
?>
Update:
I've been playing around with this and the answers that both Andrew and sachleen have provided. And ill plan to work on an AJAX alternative since you've mentioned the whole SQL Injection issue. But I am still having issues with passing the id to the remove.php file. I believe is has to do with how $notes is creating the information from the DB.
I say this because I get: Parse error: syntax error, unexpected T_STRING in /home/avonamyd/public_html/projects_php/sticky_notes/demo.php on line 24
And that is only when I include the code as is from sachleen. But when I update it to account for the single quotes I have the following code. The id is present and is passed to the remove.php file but I am still getting an error. This is when I use my code or what you've provided.
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" target="_blank" href="remove.php?id='.$row['id'].'"> </a>
</div>';
Below is what I currently have in my remove.php file:
<?php
include 'connect.php';
$_GET['id'];
function deleteNote($id){
$sql="DELETE FROM notes WHERE id='$id'";
}
$result=mysql_query($sql) or die("Error when tryin to delete note.");
?>
Update
I've added in additional echo lines throughout the remove.php and this is what I am coming up with.
<?php
include 'connect.php';
$_GET['id'];
echo $id; --doesnt show
function deleteNote($id){
echo "hello"; --doesnt show
$sql="SELECT FROM notes WHERE id='$id'";
}
echo 'hello2'; --shows
$result=mysql_query($sql) or die("Error when tryin to delete note.");
?>
Update:
Thank you for everyone's help with this project I've finally gotten the concepts to click in my head after some tinkering around. I will post the functional code below for anyone else that stumbles upon this code. =D
Thx Everyone!
demo.php
error_reporting(E_ALL^E_NOTICE);
require 'connect.php';
mysql_query("DELETE FROM notes WHERE id>3 AND dt<SUBTIME(NOW(),'0 1:0:0')");
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
$notes = '';
$left='';
$top='';
$zindex='';
while($row=mysql_fetch_assoc($query)){
list($left,$top,$zindex) = explode('x',$row['xyz']);
$id = $row['id'];
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" target="_blank" href="remove.php?id='.$row['id'].'"> </a>
</div>';
}
remove.php
<?php
include 'connect.php';
$id = intval($_GET['id']);
$sql="DELETE FROM notes WHERE id=$id";
$result = mysql_query($sql) or die("Unable to delete database entry.");
?>

It looks like you are trying to mix JavaScript and PHP. You cannot call the deleteNote() function when your link is clicked because it is a PHP function. There are a couple of ways to go about calling the PHP script to delete the note:
Use something like the following:
<?php
// ...
$id_to_delete = $_GET['id'];
if( isset($id_to_delete) ) {
$sql="DELETE FROM notes WHERE id='$id_to_delete'";
$result=mysql_query($sql) or die("Error when tryin to delete note.");
}
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
//...
while($row=mysql_fetch_assoc($query)){
//...
echo '<a id="remove_note" href="CURRENT_SCRIPT_URL?id=' . $id_to_delete . '">X</a>';
//...
}
?>
Or you could create a second script that deletes a row from the database based on the data that you pass to it and use ajax (I would recommend using jQuery for ajax functionality) to call that script with the id of the item to delete.
Remember that anyone could call your script with a GET parameter and delete a record from the database (or worse, perform an SQL injection attack), so make sure that you have some sort of safeguard in place unless you want all of your records wiped out!

You can't onclick a PHP function. You're mixing JavaScript with PHP. I would do this:
<a id="remove_note" href="remove.php?id=<?php echo $row['id']; ?>">Remove</a>
And then on remove.php get the ID using $_GET['id'] and pass that into the DELETE query.

you have 2 options.
1) make an <a href="another_php_script.php?delete=true"> (or similar), then run the delete script. (then header back to the same page you were on).
This is because you cannot run an onClick php function, you have to redirect to the other page.
2) You can use the onclick function to call an AJAX script, and execute the deleting PHP script from the page you're on - without redirecting.
Option 1 is the easy option, Option 2 is the better option to learn from.

Related

PHP Delete Function not working

Have had a look around but still struggling like no tomorrow. Just trying to get a delete button working. But its made complicated because the delete function is not completed on the one file.
Users are currently on the crud/view.php file
<?php
session_start();
if(isset($_SESSION['u_uid']))
$uid = $_SESSION['u_id'];
require_once('connect.php');
$ReadSql = "SELECT * FROM `contact` WHERE users_id=$uid ORDER BY Name";
$res = mysqli_query($connection, $ReadSql);
?>
I have a few functions but my delete button is:
<td> <input type="button" onClick="deleteme(<?php echo $r['u_uid']; ?>)" name="Delete" value="Delete"></td>
Followed by:
function deleteme(delid) {
if(confirm("Are you sure you want to Delete?")){
window.location.href='delete.php?del_id='+delid;
}
}
Leading to a crud/delete.php
<?php
session_start();
if(isset($_SESSION['u_uid'])){
require_once('connect.php');
$select = "DELETE from contact where id='".$_GET['del_id']."'";
$query = mysqli_query($connection, $select) or die($select);
}else {
print_r($_GET['del_id'])
?>
I think you can have the delete function on just the view.php and get rid of the delete.php. But I'm not sure what to do.
Many thanks!
Make sure that the variables really contain something that you expect it to have, does the u_uid was really set, try printing out your delete query to make sure that it builds a valid SQL statement.
Or you can try enclosing your table fields with back-ticks, like you did on your select statement.
It is very advisable also to use prepared statements to make your script more secured.

Request to get the id from database is not working

Hi guys I am new in php I just started learning it I am making a simple e-commerce website using xampp local server I am facing this problem when i use get method for retrieving the specific id of a row:
if (isset($_GET['id'])) {
$id = mysqli_real_escape_string($_GET['id']);
$sql = "SELECT * FROM items WHERE id= '$id'" ;
$run = mysqli_query($conn, $sql) or die ('error');
while($row=mysqli_fetch_array($run, MYSQLI_ASSOC)){
$discounted_price = $row['item_price'] - $row['item_discount'];
echo "
<div class='col-md-6'>
<h3 class='pp-title'>$row[item_title]</h3>
<img src='$row[item_image]' class='img-responsive' >
<div class='bottom'>
<div class='pull-right cutted-price text-muted'><del>$ $row[item_price]</del></div>
<div class='clearfix'></div>
<div class='pull-right disscounted-price'>$$discounted_price</div>
</div>
<h4 class='pp-dsc-title'>Description</h4>
<div class='pp-dsc-detail'>$row[item_description]</div>
</div>
";
}
}else {
echo "The request is not working";
}
The URL I am trying to access this on is below:
http://localhost/ec/items.php?item_title%20=%20Beautiful-brown-Watch&id%20=%201
I am getting the else output "the request is not working" if i remove the if statement from above and simply write in the query id = '1' or '2' the data appear on web page but when i do for a specific id it doesn't work i use mysqli_real_escape_string for get rid of SQL injection if that is not proper way to get rid of SQL injection then guide me.
You are checking for the $_GET variable id yet you are passing in the parameter item_id according to your link.
In addition to this you also have extra spaces in your query string parameters which is causing the strange %20 you are seeing in your URL, so please strip these out.
To get this working, you either need to change your URL to:
http://localhost/ec/items.php?item_title=Beautiful-brown-Watch&id=1
Or update your code to:
if(isset($_GET['item_id'])) {
$id = mysqli_real_escape_string($_GET['item_id']);
You also need to check out parameterized queries as mysqli_real_escape_string() is not the way to keep yourself safe.
A great post on this can be found here How can I prevent SQL injection in PHP?
Your code expect a parameter called id while you pass one called item_id change your URL to
http://localhost/ec/items.php?item_title=Beautiful-brown-Watch&id=1
And it should work.
Also note that when creating URL you should not include any space.

Delete mySQL table from php link not working (Blank page appears)

I've listed a list of rows from my mySQL database onto an admin page. I now simply want to add an icon beside each row giving the user the option to delete the row in question.
Here's my php delete link:
<i class="icon-circle-blank"></i>
And my delete.php file looks like:
<?php
require_once 'db.php';
global $con;
if(($_GET['action'] == 'delete') && isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "DELETE FROM quotes WHERE id = '$id'";
$query = mysqli_query($con, $sql);
}
header("location: http://localhost:81/logintest/home.php");
mysqli_close($con);
?>
From some reason when I click the link, the page just returns a blank page with no database rows being deleted. What am I overlooking?
Unless you're showing us a pseudo-code, this will not parse the PHP id variable:
delete.php?action=delete&id='$id'
you need either:
delete.php?action=delete&id=<?= $id ?>
or
delete.php?action=delete&id=<?php echo $id; ?>

how to use readmore.php?id=1 to display spacific info on another page php mysql

Sorry if my Title is crappy but I've looked everywhere and i just don't know how to do this.
OK. what i want to do is display information from a specific id from a table row.
first page
employees.php
<?php
require 'header.php';
require 'connect.php';
$sql1 = mysql_query("SELECT * FROM employees ORDER BY id ASC");
while($runrows = mysql_fetch_array($sql1)){
$employename = $runrows["employename"];
$minidescription = $runrows["minidescription"];
$bigdescription = $runrows["bigdescription"];
echo "
<!-- Employe Profile Start -->
<div class='ProfileWrap'>
<section class='Profile'>
<div class='HeadShot'>
<div class='Separator'></div>
<img width='90' height='136' alt='Employe Headshot' class='EmployeImage' src=img/headshots/".$runrows['images'] ." />
<div class='EmployeInfo'>
<legend class='EmployeName'>
<b>
Employe Name: $employename
</b>
</legend>
<div class='EmployeDes'>
<p>
Employe Descript $minidescription...
</p>
</div>
<a href='readmore.php?id=" .$id = $runrows["id"]. "' id='demo' alt='Read More'>
<div class='ReadMore'>
<b>
Read More
</b>
</div>
</a>
</div>
</div>
</section>
</div>
<!-- employe Profile End -->
";
} // close while loop
?>
<?php require 'footer.php'; ?>
second page
employe.php
<?php
require 'header.php';
require 'connect.php';
echo "<a href='index.php'>Back</a>";
$sql2 = mysql_query("SELECT * FROM employees WHERE id=$id");
while($runrows = mysql_fetch_array($sql2)){
$id = $runrows["id"];
$employename = $runrows["employename"];
$minidescription = $runrows["minidescription"];
$bigdescription = $runrows["bigdescription"];
echo "
<legend class='EmployeName'>
<b>
Employe Name: $employename
</b>
</legend>
<div class='EmployeDes'>
<p>
Employe Description: $bigdescription...
</p>
</div>
";
};
require 'footer.php';
?>
and you would click
[Read More]
then it would go to another page called readmore.php
"Click" [Read More] -> readmore.php?id=14 -> display specific info from that id from the database.
username
minidescription
->
click [Read More]
then it would show up like readmore.php?id=14 in the small address bar at the
bottom left
->
new page
->
largedescription
i want to be able to click on an item in a site that has a read more button and have it take me to another page where it displays the description info for that specific id
yes i realize I'm a complete newbie but I'm still learning and that was a crappy example of what i want to accomplish but i hope you understand what I'm trying to do none the less.
sorry if this already exists but I've looked everywhere and couldn't find what i was looking for. If someone has a link to share that can do what I've asked this question can just be deleted.
Thanks in Advance! hope someone can help me figure this out.
First, note #Matthew Johnson's answer about using Mysqli or PDO. Here are a few code specifics, though. When you generate the link to the page, you need this:
<a href='readmore.php?id=" . $runrows["id"] . "' id='demo' alt='Read More'>
Using $id = $runrows["id"] doesn't place the value into the url, it simply declares the value of the $id variable.
Then in your readmore.php file, the id can be capture from the URL using the $_GET array:
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
The mysql_* functions are deprecated, and should no longer be used. Mysqli or PDO should be used, along with prepared statements. The code as you have it is susceptible to sql injection attacks. A simplified version of what you're trying to do would look something like this:
To Link:
//this gets all the name and mini, loops through and displays....
$stmt = $mysqli->prepare("SELECT id, employename, minidescription FROM employees");
$stmt->execute();
$stmt->bind_result($id, $employeename, $minidescription);
while($stmt->fetch()) {
echo "<p><a href='readmore.php?id=$id'>$employeename</a>: $minidescription</p>";
}
The Read More:
//make sure it's set, if so assign it...
$id = (isset($_GET['id']) ? $_GET['id'] : "";
//this gets the info using the id variable from the URL...
$stmt = $mysqli->prepare("SELECT employename, minidescription, bigdescription FROM employees WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($employeename, $minidescription, $bigdescription);
$stmt->fetch();
echo "$employeename: $bigdescription";
Using mysqli and prepared statements, as shown here, protects you against bobby tables and sql injection attacks. You can learn more about mysqli from the manual. Here's a tutorial with a quick run through of how prepared statements work.
Edit:
The code above still needs a database connection. The warning of an undefined variable is saying that the $mysqli variable hasn't been defined. The fatal error is due to the fact that the prepare statement failed. To create a connection, it would look similar to this:
define("HOST", "Host URL");
define("USER", "dbUser");
define("PASSWORD", "password");
define("DATABASE", "databaseName");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
This would replace the code in your connect.php.

PHP form search for MySQL DB

I need some help getting a search function to work. I have previously coded something to work similar to this, where if I click on a hyperlink, I'm able to carry a variable forward and then assign this into an SQL script so it pulls only this one thing back from the DB. (Predefined variable, and not user input). I've tried modifying the script I've been using to allow for a form based text box to have user input which is then searched through a single database field, with a LIKE statement.
This is what I have, and it's not returning anything.
Input Form
<form class="formFormat" method="post" action="SearchResult.php">
<label class="lableInput2">Key Words</label>
<input type="text" class="textInput" name="JobDetails" />
<input type="image" src="img/blue/buttonsearch.jpg" value="search" class="buttonInput" alt="Submit Form" border="0" />
</form>
Returning Page
<?php
include('conn_mysql.inc');
include('corefuncs.php');
// create database connection
$conn = dbConnect('query');
// initialize flag
$deleted = false;
// get details of selected record
if ($_GET && !$_POST) {
// check that primary key is numeric
if (isset($_GET['JobDetails']) && is_numeric($_GET['JobDetails'])) {
$JobDetails = $_POST['JobDetails'];
}
else {
$JobDetails = NULL;
}
if ($JobDetails) {
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($result);
}
}
?>
<p><h1><?php echo ($row['JobTitle'].'<span class="jobid"> #'.$row['IDJobs'].'</span>');?></h1></p>
<p><strong><?php echo ($row['Location']); ?></strong></p>
<p><strong>£<?php echo ($row['JobValue']); ?>.00</strong></p>
<p><strong>www.companyurl.com - BAD IDEA?</strong></p>
<p><strong>Open for Bidding</strong></p>
<br />
<p><span class="jobid">Job Posted: <?php echo ($row['JobPostDate']); ?></span></p>
<p><?php print ($row['JobDetails']); ?></p>
<p><span class="jobid">Job Deadline: <?php echo ($row['JobDeadline']); ?></span></p>
I know that I need to loop the output, so it displays more than one, but at the moment it simply returns the following error for every field (obv the line changes depending on what's trying to extract.
"( ! ) Notice: Undefined variable: row in
C:\wamp\www\ReEmployWork\SearchResult.php on line 54"
Can anyone assist? I'm a bit lost with this, and I believe I'm either going in the wrong direction or just missing something.
You missed $ before the variable name. Instead of:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
write:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$JobDetails%'";
You left your $ before JobDetails in you query.
Also remeber to use http://php.net/manual/en/function.mysql-real-escape-string.php
A suggestion:
$escaped_value = mysql_real_escape_string($JobDetails)
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$escaped_value%'";
For future readers. I scrapped the code I tried to modify and I took it from the beginning. There's enough information above for anyone to do this. Have a go, and you may end up with a result similar to what I coded.
$JobDetails = $_POST['JobDetails'];
$JobDetails = mysql_real_escape_string($JobDetails);
$sql = "SELECT * FROM `jobs` WHERE `JobDetails` LIKE '%{$JobDetails}%'";
$result = mysql_query($sql) or die (mysql_error());
?>
The above is what I coded and it runs like a dream. You make a lot more mistakes modifying code than you do, if you just code from scratch, so if you're learning dabble and play with code already wrote, but if you need something yourself which is unique then you're best starting from scratch.

Categories