Delete button for SQL - php

I have a member/account site that posts "notes" and saves them in your account. When someone post's a note, each note gets an edit and a delete button. I want the delete button to delete the corresponding post, however its deleting whichever note is on top. I assume the problem lies within either the else when the delete button is pressed or during the while when the button is created. Wouldn't I need a way to assign the buttons an id?
Thanks in advance.
<!-- connections.php connects to the database -->
<?php require 'connections.php'; ?>
<!-- check to make sure the user is logged in,
if not then redirect them to login.php -->
<?php session_start();
if(isset($_SESSION["UserID"])){
} else {
header('Location: Login.php');
die();
}?>
<!-- $result is a query containing all the notes
of the current user -->
<?php $UserID = $_SESSION["UserID"];
$result = mysqli_query($con, "SELECT * FROM notes WHERE UserID = '$UserID'");
?>
<!-- when you click 'save' upload the new note
to the database and refresh the page.
when you click 'delete' remote the note
that goes with that button from the database -->
<?php if(isset($_POST['save'])) {
session_start();
$note = $_POST['note'];
$UserID = ($_SESSION["UserID"]);
$sql = $con->query("INSERT INTO notes (UserID, note)Values('{$UserID}','{$note}')");
header('Location: Account.php');
} else if (isset($_POST['delete'])){
$result = mysqli_query($con, "SELECT * FROM notes WHERE UserID = '$UserID'");
$row = mysqli_fetch_array($result);
$noteID = $row['noteID'];
$UserID = ($_SESSION["UserID"]);
$sql = $con->query("DELETE FROM notes WHERE noteID = '$noteID'");
header('Location: Account.php');
} else if (isset($_POST['edit'])){
}?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>My Account</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h1 class="titleAct">Welcome</h1>
<form action="" method="post" name="notesubmit" id="notesubmit">
<div>
<textarea name="note" cols="50" rows="4" form="notesubmit" id="noteinput">New Note
</textarea>
</div>
<input name="save" type="submit" class="button" id="save" value="Save">
<!-- Whenever a note is saved, print out the
note with timestamp followed by the edit
and delete buttons for each note -->
<?php while ($row = mysqli_fetch_array($result)): ?>
<?php $note = $row['note'];?>
<?php $date = $row['time'];?>
<div id="note">
<p class="note"><?php echo $date; ?></br> ---------------- </br><?php echo $note; ?></p>
</div>
<input name="edit" type="submit" class="button" id="edit" value="Edit">
<input name="delete" type="submit" class="button" id="delete" value="Delete">
<?php endwhile; ?>
</form>
<div>
<a class="link" href="Logout.php">Logout</a>
<div>
<a class="link" href="Deactivate.php">Deactivate My Account</a>
</div>
</div>
</body>
</html>

You have a logical error... Your not sending back the ID of the note you want to delete anywhere, you just say you want to delete something, then fetches the list of notes from the database, and deletes the first that pops in...
What I would do, is change the delete button to a link, and sett a query parameter ($_GET['noteID']) to select which ID to delete...
Then I would select the NoteID from the database, but also make sure the user tries to delete his own post, and not someone elses...
Good luck :)

Related

PDO $_GET the id of a task to delete a specific task in the database when the user click the delete button of that task

I have a problem to get the id of a task in order to delete that task when the user clicks on the delete button of that task in the UI. I have two tables, one is the "To-do Task" table, and the other is the "Completed Task" table. In the code, I did ask the user what task in what table they want to delete via form by using the task's id and the table name. Now I do not want to use the form, but I want to have a delete button next to each task in each table so that the user just needs to click on that button to delete the task. Can you teach me how to do it? Thank you
<?php
session_start();
require 'connect.php';
$owner = $_SESSION['name'];
//delete data in the table the user want based on id of the data
if (isset($_POST['delete'])) {
$section = $_POST['delete_com_in'];
$task_id=$_POST['delete_com_in_id'];
$deleteQuery="DELETE FROM $section WHERE id=:task_id";
$preparedDeleteStatement = $conn->prepare($deleteQuery);
$preparedDeleteStatement->bindValue(':task_id',$task_id);
$valueDelete=$preparedDeleteStatement->execute();
}
//fetch data into table (incomplete and complete)
$displayQuery="SELECT * FROM incomplete where owner=:owner";
$displayTask= $conn->prepare($displayQuery);
$displayTask->bindValue(':owner', $owner);
$displayTask->execute();
$allTask=$displayTask->fetchAll();
echo "<table class=\"incomplete_table\"><caption>To-do Tasks</caption><tr><th>ID</th><th>Title</th><th>Description</th><th>Due Date</th><th>Time</th></tr>";
if(count($allTask) > 0)
{
foreach ($allTask as $row) {
echo "<tr><td>".$row["id"]."</td><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["due_date"]."</td><td>".$row["time"]."</td></tr>";
}
}
$displayQueryComplete="SELECT * FROM complete where owner=:owner";
$displayTaskComplete= $conn->prepare($displayQueryComplete);
$displayTaskComplete->bindValue(':owner', $owner);
$displayTaskComplete->execute();
$allTaskComplete= $displayTaskComplete->fetchAll();
echo "<table class=\"complete_table\"><caption>Completed Tasks</caption><tr><th>ID</th><th>Title</th><th>Description</th><th>Due Date</th><th>Time</th></tr>";
if(count($allTaskComplete) > 0)
{
foreach ($allTaskComplete as $row) {
echo "<tr><td>".$row["id"]."</td><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["due_date"]."</td><td>".$row["time"]."</td></tr>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./main_list.css">
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
<script src="./add_task.js" defer></script>
<title>Main List</title>
</head>
<body>
<div id="container">
<button id="buttonMainList">Logout</button>
<p id="userNameHere"><?php echo $_SESSION['name']; ?></p>
</div>
<h1 id="inform">TO-DO LIST</h1>
<div id="menu">
<label for="action">Choose an action:</label>
<select id="action" name="action" onchange='onSelectChangeHandler()'>
<option value="delete">Delete</option>
</select>
</div>
<!--delete form-->
<div id="delete">
<div id="delete_task_form">
<p id="delete_task">Delete Task</p>
<form id="delete_form" name="delete_form" method="post">
<div id="delete_section">
<input type="radio" id="delete_com_complete" name="delete_com_in" value="complete">
<label for="delete_com_complete">Completed</label>
<input type="radio" id="delete_com_incomplete" name="delete_com_in" value="incomplete">
<label for="delete_com_incomplete">Incomplete</label>
</div>
<div id="delete_section_id">
<label for="delete_com_in_id">What ID?</label>
<input type="text" id="delete_com_in_id" name="delete_com_in_id"><br>
</div>
<input id="submit_delete_form" type="submit" name="delete" value="Delete">
</form>
<br>
</div>
</div>
</div>
</body>
Well, it's not a correct way of work but without a form you can use the tag to pass throught get the id of the task to delete:
<html>
Delete button
</html>
Also, you need to known the table that the user want delete so you need to create two buttons each one will represent one table:
<html>
Delete button table 1
Delete button table 2
</html>
98 is an exemple of a id. When you have passed the id of the task you only have to receive it by $_GET:
<?php
if(isset($_GET["task"])){
$Task=$_GET["task"];
}
?>
Once you have the id you have to do the same with the table:
<?php
if(isset($_GET["table"])){
if($_GET["table"]=="To-do Task"){
$Table="To-do Task";
}else{
$Table="Completed Task";
}
}
?>
Finally you only have to delete the task depending the table:
<?php
if($Table=="To-do Task"){
$deletetask= $con->prepare("DELETE FROM `To-do` Task WHERE ID=?;");
$deletetask->execute([$Task]);
}else{
$deletetask= $con->prepare("DELETE FROM Completed Task WHERE ID=?;");
$deletetask->execute([$Task]);
}
?>
Remember always sanitize and validate inputs from the users or values than can be manipulated by the user

Share $_POST variables to another page meaning the main page to the ajax response page?

Here's my situation I have a perfect membership system I realized it's been easier to just use a form with some hidden input with predetermined values created from previous button clicks from previous pages to send the user id and the other user id aka the other member to other pages which the post data becomes variables eventually in each page deeper in each code document which are eventually use in SQL statements. My method has been working but now I have a new problem now I have a private messaging system page where users can send private messages to each other so I found this really cool script which I later semi modify it to work on my membership system but it consist of two main pages that are used to make it work completely the first page consist of pretty much the private messaging system primary components the second page aka chat.php is a AJAX response page designed to show new messages. So how can I share the main page post data variables with the AJAX response page. I tried to put the ajax response page code on the same page of the main page but it looked strange and it gave me strange results. Note in this situation the partner_id is aka the other user id and since the first include of each page consist of the login member id already aka messenger_id it's just the other user id i'm concern of aka the partner_id and just know that the SQL column call message belongs to the messenger_id the partner_id in the SQL database is designed to show who the login member aka messenger_id talked to (partner_id) Here's the code
MAIN PAGE
<?php
include("0/instructions/php/session.php");
$messenger_id = $user_id;
$partner_id= $_POST['partner_id'];
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta charset="UTF-8">
<title>Chat System in PHP</title>
<link rel="stylesheet" href="style.css" media="all"/>
<script>
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
document.getElementById('chat').innerHTML = req.responseText;
}
}
req.open('GET', 'chat.php', true);
req.send();
}
setInterval(function() {
ajax()
}, 1000);
</script>
</head>
<body onload="ajax();">
<div class="main_container">
<div id="container">
<div id="chat_box">
<div id="chat"></div>
</div>
</div>
<form method="post" action="">
<input type="text" name="messenger_id" placeholder="messenger_id" value="<?php echo $messenger_id; ?>"/>
<textarea name="message" placeholder="enter message"></textarea>
<input type="text" name="partner_id" placeholder="partner_id" value="<?php echo $partner_id; ?>"/>
<input type="submit" name="submit" value="Send it"/>
</form>
<?php
if(isset($_POST['submit'])) {
$messenger_id = $_POST['messenger_id'];
$message = $_POST['message'];
$partner_id = $_POST['partner_id'];
$query = "INSERT INTO messages_x (messenger_id,message,partner_id) values ('$messenger_id','$message','$partner_id')";
$run = $connect->query($query);
if($run) {
echo "<div id='hide_audio'><embed loop='false' src='chat.mp3' hidden='true' autoplay='true'/></div>";
}
}
?>
</div>
</body>
</html>
THE AJAX RESPONSE PAGE AKA CHAT.PHP
<?php
include("0/instructions/php/session.php");
$messenger_id = $user_id;
$partner_id = $_POST['partner_id'];
$query= "SELECT * FROM messages_x WHERE messenger_id='$messenger_id' AND partner_id='$partner_id' ORDER BY messenger_id DESC";
$run = $connect->query($query);
while($row = $run->fetch_array()) :
$messenger_id = $row['messenger_id'];
?>
<div id="chat_data">
<span style="color:green;"><?php echo $row['messenger_id']; ?></span> :
<span style="color:brown;"><?php echo $row['message']; ?></span>
<span style="float:right;"><?php echo formatDate($row['date']); ?></span>
</div>
<?php
endwhile;
$query_other= "SELECT * FROM messages_x WHERE messenger_id='$partner_id' AND partner_id='$messenger_id' ORDER BY messenger_id DESC";
$run_other = $connect->query($query_other);
while($row_other = $run->fetch_array()) :
?>
<div id="chat_data">
<span style="color:gold;"><?php echo $row_other['messenger_id']; ?></span> :
<span style="color:purple;"><?php echo $row_other['message']; ?></span>
<span style="float:right;"><?php echo formatDate($row_other['date']); ?></span>
</div>
<?php
endwhile;
In this example the hidden form inputs are shown for simple explanation here and as a result I want it to look like this.

PHP query won't work from HTML href link

Am creating a webpage which allows me to search for locations by county. I am trying to create an href link on my basic homepage which will call to a Php function and then display results from my Sql database.
Not sure why but when I click on the href link the homepage just goes blank, no values returned. Have been over code and database, have shown to a few friends and can't figure out what's wrong. Any help appreciated!
This is my index.php main homepage code (with href about halfway down)
<!DOCTYPE HTML>
<?php
include("includes/db.php");
include("getAntrim.php");
include("functions/functions.php");
?>
<html>
<head>
<link rel = "stylesheet" href="styles/styles.css" media = "all"/>
<title>Location Scout</title>
</head>
<body>
<!-- Main container starts -->
<div class ="main_wrapper">
<div id="form">
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="user_query" placeholder="Search for location"?>
<input type="submit" name="search" value="search"/>
</form>
</div>
<div class ="content_wrapper">
<div id ="left_sidebar">
<div id="sidebar_title">Search by County</div>
Antrim<br></br>
<div id ="content_area">
<div id ="products_box">
<!-- THIS IS WHERE FETCHED DATABASE INFO WILL GO -->
<?php
getAntrim();
?>
</div>
</div>
</div>
<!-- Main container ENDS -->
</div>
</div>
</body>
</html>
This is my getAntrim.php function, which should sort through sql database and then return stated values.
<?php
include ("includes/db.php");
if (isset ($_GET['getAntrim'])) {
$get_loc_co = "select * from locations where county='Antrim'";
$run_loc_co = mysqli_query($db, $get_loc_co); //Gets data from db and presents on main page
$count = mysqli_num_rows($run_loc_co);
if ($count==0) {
echo "<h2>No locations found in this category.";
}//if
while ($row_loc_co=mysqli_fetch_array($run_loc_co)) {
//variable to store values
$loc_id = $row_locations['loc_id'];
$loc_name = $row_locations['loc_name'];
$town = $row_locations['town'];
$county = $row_locations['county'];
$productions = $row_locations['productions'];
$disabled = $row_locations['dis_access'];
$parking = $row_locations['parking'];
$visitor = $row_locations['vis_facs'];
$transport = $row_locations['public_trans'];
$cost = $row_locations['cost'];
$accom = $row_locations['accom'];
$latitude = $row_locations['latitude'];
$longitude = $row_locations['longitude'];
$description = $row_locations['loc_desc'];
$keyword = $row_locations['loc_keyword'];
$loc_image = $row_locations['loc_img'];
echo "
<div id= 'single_location'>
<h3>$loc_name</h3>
<img src = 'Admin_area/location_images/$loc_image' width='180' height = '180'/><br>
<p><b>Productions: $productions </b></p>
<p><b>Description: $description </b></p>
</div>
";
}//while
}//if
?>
Am first time poster, so hopefully have posted this ok! Any advice appreciated.
you're checking for a query parameter, which you're NOT passing in:
Antrim<br></br>
if (isset ($_GET['getAntrim'])) {
^^^^^^^^^
$_GET contains url query parameters, e.g. example.com?foo=bar (the foo=bar portion). Since you have NO query parameters in your href, the isset() properly returns false, and your entire db code section is simply ignored.
You probably want
Antrim<br></br>
^^^^^^^^^^
to make this work as-is.

PHP delete current 'note' not working

I'm generating a delete button for each 'note' the user creates. However, no matter which delete you click, its deleting the most recently saved note, not the one corresponding to the note. I assume that something is wrong with my hidden field 'deleteID'.
<!-- connections.php connects to the database -->
<?php require 'connections.php'; ?>
<!-- check to make sure the user is logged in,
if not then redirect them to login.php -->
<?php session_start();
if(isset($_SESSION["UserID"])){
} else {
header('Location: Login.php');
die();
}?>
<!-- $result is a query containing all the notes
of the current user -->
<?php $UserID = $_SESSION["UserID"];
$result = mysqli_query($con, "SELECT * FROM notes WHERE UserID = '$UserID'");
?>
<!-- when you click 'save' upload the new note
to the database and refresh the page.
when you click 'delete' remote the note
that goes with that button from the database -->
<?php if(isset($_POST['save'])) {
session_start();
$note = $_POST['note'];
$UserID = ($_SESSION["UserID"]);
$sql = $con->query("INSERT INTO notes (UserID, note)Values('{$UserID}','{$note}')");
header('Location: Account.php');
} else if (isset($_POST['delete'])){
$deleteID = $_POST['deleteID'];
$sql = $con->query("DELETE FROM notes WHERE noteID = '$deleteID'");
header('Location: Account.php');
} else if (isset($_POST['edit'])){
}?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>My Account</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h1 class="titleAct">Welcome</h1>
<form action="" method="post" name="notesubmit" id="notesubmit">
<div>
<textarea name="note" cols="50" rows="4" form="notesubmit" id="noteinput">New Note
</textarea>
</div>
<input name="save" type="submit" class="button" id="save" value="Save">
<!-- Whenever a note is saved, print out the
note with timestamp followed by the edit
and delete buttons for each note -->
<?php while ($row = mysqli_fetch_array($result)): ?>
<?php $note = $row['note'];?>
<?php $date = $row['time'];?>
<?php $noteID = $row['noteID'];?>
<div id="note">
<p class="note"><?php echo $date; ?></br> ---------------- </br><?php echo $note; ?> </p>
</div>
<input name="deleteID" type="hidden" id="hidden<?php echo $noteID;?>" value="<?php echo $noteID; ?>">
<input name="delete" type="submit" class="button" value="Delete">
<?php endwhile; ?>
</form>
<div>
<a class="link" href="Logout.php">Logout</a>
<div>
<a class="link" href="Deactivate.php">Deactivate My Account</a>
</div>
</div>
</body>
</html>
I am thinking its not the delete at all - but the div with the note in it - each has the same id since they are in the while loop and therefore every note div has the id of "note"
<div id="note">
its should be
<div id="note<?php echo $noteID;?>";
The error seems to be in the name of the input. Should be the same as the value you set in the ID part.
Like this :
<input name="hidden<?php echo $noteID;?>" type="hidden" id="hidden<?php echo $noteID;?>" value="<?php echo $noteID; ?>">
Otherwise, all your inputs have the same name, and it takes the last one to do the query.
EDIT
Put the name of the value you want to delete directly in the submit button like this :
<input name="delete-<?php echo $noteID;?>" type="submit" class="button" value="Delete">
Then you can get the value in $_POST array and explode() the value on - separator to get the ID value.
you also have multiple submit inputs for the one form - one to trigger the save and one each for each echo-ed delete note, so triggering the delete submit function is going to first trigger the save submit - therefore $_POST['save'] will be acted on before the $_POST['delete']. This could be the issue behind the action of altering the last input note rather than the one that was the trigger action.
I would suggest splitting off the add note function to a different form than the delete note functions. You can have the same if else logic and this should work as expected in the new version since you are actually posting the information you are expecting to.

How do I check which input button has been pressed in PHP?

so I'm new to php and I have two buttons on this html page here (the id value is included in the url):
<!DOCTYPE html>
<head>
<title>StoryBlox is a Social Story Builder Tool</title>
<meta charset="utf-8">
<!-- these support the header/footer formatting -->
<link type="text/css" rel="stylesheet" href="css/main.css">
<link type="text/css" rel="stylesheet" href="css/header_footer.css">
<script src="js/header.js"></script>
<?php //include_once 'confirm_login.php'
include_once 'story_manager.php';
include_once 'open_connection.php';
//include_once 'functions.php';
//sec_session_start();
if(isset($_GET['id'])){
$str_id = $_GET['id'];
$draft_id = get_story_attribute($str_id, 'draft');
}else{
echo "Invalid story id.";
echo "<br>";
}
?>
</head>
<body>
<div id="wrapper_main">
<div id="wrapper_content">
<?php include_once 'header.php'; ?>
<h1>Welcome to StoryBlox Create Story!</h1>
</div>
<!-- menu -->
<!--<div id="inputs"> -->
<form id="create_form" action="save_story.php?id=<?php echo $str_id?>" method="POST">
<input type="text" name="storyTitle" id="title" placeholder="Enter title." autofocus/><br>
<textarea rows="4" cols="50" name="storyDesc" id="description" placeholder="Enter description here."></textarea>
<div id="footer">
<input type="button" name="draftBtn" onclick="this.form.submit()" value="Save as Draft"/>
<input type="button" name="finalBtn" onclick="this.form.submit()" value="Finished!"/>
</div>
</form>
</div>
</div>
<?php include_once 'footer.php'; ?>
</body>
When I click one of these two buttons, I'm brought to this php document here:
include_once 'open_connection.php';
include_once 'story_manager.php';
$mysqli = open_connection();
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(isset($_POST['draftBtn'])){
$title = $_POST['storyTitle'];
$desc = $_POST['storyDesc'];
$str_id = $_GET['id'];
update_story_title($str_id, $title);
//update_story_description($str_id, $desc);
header('Location: createStory.php');
}
elseif(isset($_POST['finalBtn'])){
$title = $_POST['storyTitle'];
$desc = $_POST['storyDesc'];
$str_id = $_POST['storyID'];
update_story_title($str_id, $title);
//update_story_description($str_id, $desc);
save_draft_as_completed($str_id);
header('Location: ../home.php');
}else{ echo "failed";}
}?>
And I always get "failed" printed out on my page. I've been Googling this for hours and I don't understand where I'm going wrong here. If anybody could help that would be appreciated. Also, if anyone could shed some light on what the equivalent to
<input type="textarea">
would be that would be great. Thanks!
Use
<input type="submit" name="draftBtn" value="Save as Draft"/>
instead of the button types with their onclick events.
try to use submit tag instead of button.
and if you want to use button tag then you can pass value through hidden field. set value of hidden field on click event.

Categories