Process database delete action in the same PHP page with post - php

I'm building PHP application for process employee leave records. In this application the main screen populate database records and action buttons. when user click the action button it take the database id from the table and go through another file to delete that record and then redirect back to the same page. This mechanism implemented using HTML _GET method. that means anyone can see the row ID in the URL feed and if anyone request this url with different row ID, PHP file delete the record since any other security measures not taken place in to prevent that. and also this application not using any kind of session.
this is my href code for the task I mentioned above.
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";
and this is my rejectone.php code
<?php
$lid =$_GET['id'];
include 'database.php';
$accval = "Accept";
try {
$query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = '$lid'";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $id);
$stmt->execute();
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
header( "refresh:0;url=bs.php" );
?>
I have two questions
1.) How can I run the rejectone task inside the same PHP file without redirecting to another PHP file
2.) How can I use HTML _POST method instead of get method to transfer data if I still use jejectone.php file
thanks!!

First of all change your line:
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";
to
echo 'Cancal';
If you haven't included jQuery on your site, you can do it by adding this script to your page, just before closing
</head> tag
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
Add this JavaScript file to the bottom of your page, just before closing </body>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.delete-item', function(e){
e.preventDefault();
if(!confirm('Are you sure you want to delete this item?')) return false;
$.post('bs.php', {'id': t.attr('primary-key'), 'delete_item': 1}, function(e){
window.location = 'bs.php';
})
})
})
</script>
Copy your rejectone.php to bs.php, but make these changes:
if(isset($_POST['delete_item']))
{
$lid = (int)$_POST['id'];
include 'database.php';
$accval = "Accept";
try {
$query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = :lid ";
$stmt = $con->prepare( $query );
$stmt->bindParam(':lid', $lid );
$stmt->execute();
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
That is it.

Use ajax post method. See Full example of accepted solution with sample code for more details here : Delete MySQLi record without showing the id in the URL
Then using jquery remove that record from the page which will give more good UI experience.

Related

Implement Ajax for a PHP Function

I am trying to work implement ajax due to maximum site load which PHP causes. But I am not aware of where I am making a mistake here. it is an anchor tag, when it is clicked the status of the particular row should be changed to a string which is hard coded.
PHP WAY
USERDETAIL.PHP
Next
Then it triggers This (IGNORE SQL INJECTION)
if(isset($_GET['changeStatus'])){
$id = $_GET['changeStatus'];
$user=$_SESSION['user'];
$sql = "select * from productOrder where id = ".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
$sql = "update productOrder set prodStatus = 'Ready', By='".$user."' where id=".$id;
if(mysqli_query($conn, $sql)){
header("Location:USERDETAIL.php");
}
}
}
According to this way, it works neat, but the userdetail.php would refresh anyways which is a lot time consuming. Then tried AJAX way is below.
Next
and that hits to
$(document).ready(function() {
$(".changeStatus").click(function(event){
event.preventDefault();
var status = "Ready";
var id = $(this).attr('data-id');
$.ajax({
url : 'action.php',
method : 'POST',
data : {status : status , id : id},
dataType: 'html',
success : function(response){
console.log(response);
}
});
});
});
and in the action.php it is (IGNORE SQL INJECTION AGAIN)
if(isset($POST['prodStatus'])){
$status = $_POST['prodStatus'];
$id = $_POST['id'];
$sql = "update productOrder set prodStatus= '$status' where id=".$id;
$result = mysqli_query($conn, $sql);
if($result){
return 'Updated';
}
}
The output is nothing happens. in the console it is just adding int values. I know I am making a mistake, or understood AJAX in a wrong way. it is just one button click and the string in SQL should be updated without an input text / modal. Please suggest what should be improved?
Also instead of having a seperate action php for these actions, can I do all these in userdetail.php itself with Ajax? is it possible?
Thanks in advance.
As B_CooperA pointed out, $POST should be $_POST.
Also, in $.ajax script data object your property name is status and in action.php you are checking it by prodStatus.
Furthermore, you should check the errors PHP is throwing in your script by enabling error reporting: error_reporting(E_ALL);
It's better to separate ajax calls from your view files. You can create a Class to handle all of your ajax calls (You should also consider authenticating your calls as per your use cases).

How to handle AJAX error if sql update fails?

I have a php file, which updates the SQL, if the "follow this user" button is clicked, and an AJAX calls this PHP file. The code below works, it follows the user! My problem is: If, for some reason the SQL update fails, I want the AJAX to drop an error message (e.g. an alert), but I really don't know how this could be possible. The AJAX doesn't know whether the update succeeded or not.
Here's my code:
PHP
if(!empty($_GET['a']) and $_GET['a']=='follow')
{
$id = sql_escape($conn,$_GET['id']);
$me = $user2[0];
//the user's id who clicks on the follow button
$query = sql_fetch(sql_query($conn, "select * FROM
forum where id='$id'"));
//check who created this forum, so we know who to follow
$follow_this_user = $query['user'];
//the user to follow
$now = date('Y-m-d H:i:s');
$already_follow_user = sql_fetch(sql_query($conn,
"SELECT * FROM follow WHERE user_id=".$me." AND
followed_user =".$follow_this_user." "));
//check if user already followed by this user
if(empty($already_follow_user[0])) {
//if not followed
sql_query($conn,"INSERT INTO follow
(user_id, followed_user, date) VALUES
('".$me."', '".$follow_this_user."', '".$now."');")
or die(mysqli_error($conn));
}
}
AJAX:
$(document.body).on('click', '.followable', function(){
//User clicks on the follow text, which has "followable" class
$.ajax({
//type: 'GET',
url : '/ajax/ajax_follow.php?a=follow&id=<?php print $topic[id]; ?>'
//the $topic['id'] is the id of the current topic, which
//I need to know who created this forum, to follow that user
//(as mentioned above in the php code)
});
I need data and error, but no idea how to get them working. I tried many things, but I just can't get the data.
Add this to your ajax request:
success: function(data) {
alert(data);
}
And simply echo something on your PHP page.
For example:
$result = mysql_query($sql);
echo $result;
If you want to recieve more data, JSON is your friend.

How to update and output a database without reloading the page

I have data which is a name. And I am having an input type=text where the value is equals to the name, together with a button type=submit. So what i'm trying to do is that, i want to change and update the name in my database and also output the new name without reloading the page at once because I want to run a JS function (Not Alert but a Toast Notification) which is I cannot do. So to shorten, ( EDIT -> UPDATE -> SHOW = without reloading the page).
EDIT:: I'm sorry I forgot to mention. I know jQuery and AJAX is the solution but I am having trouble understanding AJAX not unlike jQuery.
profile.php (FORM CODE)
<form action="profile.php" method="POST">
<input type="text" id="changename" name="changename" class="form-control" placeholder="New Name" required>
<button id="btnchange" type="submit"></button>
</form>
profile.php (PHP CODE)
<?php
if(isset($_POST['changename'])) {
require 'connect.php';
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
header('location: profile.php');
// MY JS FUNCTION HERE //
}
mysqli_close($conn);
}
?>
How to update and output a databse without reloading the page? what u looking for is AJAX.
I know you have selected the answer, but there's an extra information that you need that might help you in the long run
The are some good ajax tutorials you can follow in the web
Ajax Introduction
What is Ajax ?
And many more you can find on the web.
This is what u need to do, first your form method is GET and on your php script you are requesting an $_POST therefore this will generate an undifined notice error,changename : notice : undifined variable changename so the solution is to use one method in a single form if your form is $_GET you use $variable = $_GET['fieldname'] if form method is POST on your server side use $variable = $_POST['fieldname']; not the way you did. So lets change your form method to POST Then this is what u should do.
edit.php
Update
<script type="text/javascript">
$('document').ready(function(){
$('form').on('submit',function(event){
event.preventDefault();//prevent the form from reloading the page when submit
var formData = $('form').serialize(); // reading form input
$.ajax({
type :'POST',
data : formData,
url : 'profile.php',
dataType : 'json',
encode : true,
success : function(response){
//response = JSON.parse(response);
if(response == "ok"){
$('#success').html('profile updated success');
setTimeout(' window.location.href = "profile.php"; ', 6000); // redirecting
}else{
//could not update
$('#error').html(response);
}
},
error : function(e){
console.log(e); // debugging puporse only
}
});
});
});
</script>
That's what you need on the frontend side.. Please note if you have more than one form in a single page then do not use $('form').on('submit',function(event){}); you then give each form a unique ID then on replace the form on jquery/ajax with the iD of the form u wanna submit.
Then your server side.
I have noticed that you have header('location: profile.php'); that's
for redirecting, since we are sending ajax request to the server and
back to the client, you don't redirect on the server side, your
redirect using the client side after you have received the response
you expected from the server. I have commented that section where I do
redirecting with client side, on the script above.
profile.php
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
$message = 'ok'; // success
}else{
$message = 'system error could not update please try again later';
}
echo json_encode($message);//sending response back to the client
mysqli_close($conn);
}
?>
That's all you need, note you need to validate all your inputs fields in both the client and server side before using them.
I would also advice you to learn more about prepared statements, using mysqli or PDO they are very easy to use and very safe.
running a query like this : $sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'"; is very unsafe, your inputs are not validated and not filtered and sanitized.
so with prepared statements its easy like :
profile.php prepared
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
//prepare and bind
$sql = $conn->prepare("UPDATE login SET login_name= ? WHERE user_id= ? ");
$sql->bind_param("si",$newname,$user_id);
if($sql->execute()){
$message = 'ok';
}else{
$message = 'Error Could not update please try again later';
}
echo json_encode($message);
$conn->close();
}
?>
$sql->bind_param("si",$newname,$user_id); This function binds the parameters to the SQL query and tells the database what the parameters.
are.By telling mysql what type of data to expect, we minimize the risk of SQL injections.
First thing to do in your form is to change your form method to POST (and not GET) as you try to retrieve "changename" by POST method.
So change this:
<form action="profile.php" method="GET">
by this:
<form action="profile.php" method="POST">

Getting from Javascript to PHP for Deleting from Database

I have a link that's generated from a entry in a database, and I need to be able to delete that link. I have the DELETE query in my PHP, and a JavaScript confirm that works just fine, but confirming won't activate the PHP query. Here's the code:
JavaScript:
<script language="JavaScript" type="text/javascript">
function deldoc(docid, docname)
{
if (confirm("Are you sure you want to delete '" + docname + "'"))
{
window.location.href = '<?php echo DIREMPLOYEE;?>?deldoc=' + docid;
}
}
</script>
PHP:
if(isset($_GET['deldoc'])){
$deldoc = $_GET['deldoc'];
$deldoc = mysql_real_escape_string($deldoc);
$sql = mysql_query("DELETE FROM Documents WHERE docid = '$deldoc'") or die(mysql_error());
$_SESSION['success'] = "Document Deleted";
header('Location: ' .DIREMPLOYEE);
exit();
}
When I press the OK button on the Confirm popup, it takes me to the Index page, but it's not deleting the document, and it's not giving me an error. Instead, it just tacks the docid onto the end of the directory URL, so it looks like this:
http://domain.com/employee?deldoc=7
Any ideas on how I can fix this?
Your SQL query should be something like this:
mysql_query("DELETE FROM Documents WHERE docid = '$deldoc'")
Warning:
mysql_ functions are deprecated, use mysqli or PDO. Also your code is not safe. It's vulnerable to SQL injections.

page not refreshing after clicking delete button

good day
need some help here, my Delete button works but page is not automatically refreshing after i clicked the delete button. i still need to manually retrieve the data from db and it would reflect that data is deleted already...
here is my code for delete php: how can i make this to refresh the page automatically?
<?php
require 'include/DB_Open.php';
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl WHERE ticket in (" . $idtodelete . ")";
$myData = mysql_query($query);
echo "DATA DELETED";
if($myData)
{
header("Location: delete.php");
}
include 'include/DB_Close.php';
?>
I suggest fetching the data after your delete logic. Then the delete logic will be executed before fetching the tickets.
Then a redirect to the same page isn't even necessary.
//
// DELETE
//
if (isset($_POST['delete'] && isset($_POST['id'])) {
// Do delete stuff,
// notice delete variable which would be the name of the delete form button e.g.
// If you like, you can still echo "Data deleted here" in e.g. a notification window
}
//
// FETCH data
//
$query = "Select * FROM tbl";
...
if you use post method better with this
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl WHERE ticket in (" . $idtodelete . ")";
if (mysql_query($query))
{
header("Location: delete.php");
} else {
echo "Can not delete";
}
}
As suggested on one of the comments, and on the php documentation:
http://it2.php.net/manual/en/function.header.php :
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Basically you have to take out the :
echo "DATA DELETED";
What's the point to try to echo that string if the page is going to be redirected anyway?
If you want to make it fancy you could use Ajax to delete it, and trigger a setTimeout() on JavaScript x seconds after showing the message.
Or if you really really really really, REALLY, want to do it this way, you could disable the errors report/display (using error_reporting(0) and ini_set('display_errors', 'Off'). By experience I know that it will work, but it's nasty and extremately ultra highly not recommended

Categories