delete a certain comment in comment-reply system in php - javascript

I have created a comment-reply system in php. It is similar to wall in facebook. User writes a comment and then post it in "wall". I use the following tables in my database to hold comments: comments(comments_id, comment, comment_date, user, comment_hash, flash) and table users that hold user's details: users(user_id, name, surname). Everything works perfect, the only problem is that I cannot delete a certain comment. Deleting a comment means to set flag=1 for this comment in my database.
On each comment there is a link named "delete". When user press delete, a light box starts in javascript and user by pressing delete, the function "deletepost" is executed. My only problem is that this function sets flag=1 to all comments in my databe and not for the certain comment that I press delete. Any idea how to improve my code?
I use the following function in order to display comments:
<?php
function getComments(){
$session_user_id = $_SESSION['user_id'];
$comments = "";
$sql = mysql_query("SELECT * FROM comments WHERE (`flag`=0) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'> Write your first posts ...</div> ";
}
else{
while ($row= mysql_fetch_assoc($sql)) {
$comment_id = $row['comments_id'];
$hash = $row['comment_hash'];
$personal_1 = mysql_query("SELECT `user_id`, `name`, `surname`, `email`, `profile` FROM `users` WHERE `user_id`='{$row['user']}' ");
while ($run_personal_1= mysql_fetch_assoc($personal_1)) {
$comment_user_id = $run_personal_1['user_id'];
$comment_user_name = $run_personal_1['name'];
$comment_user_surname = $run_personal_1['surname'];
}
// displays comment that includes user's name and surname and hash
$comments .= " $comment_user_surname $comment_user_name $hash";
$comments .= ".$row['comment'].";
//---- at this point I insert a delete link , that when user presses it a javascript light box ask user if wants to delete the comment. If user press the delete button it is called the function named "deletepost".
//---- first checks if the comment is from the user that is logged in ($session_user_id) in order to have the right to delete post
if($comment_user_id == $session_user_id){
if(isset($_POST['submit_2'])) {
deletepost($session_user_id, $comment_id);
header('Location: wall.php');
}
$comments .= <<<EOD
<font color='grey' >Delete</font>
<div id="light" class="white_content">
<form action="$_SERVER[PHP_SELF]" method="post">
<input type="submit" name="submit_2" value="Delete Post ">
</form>
<button>Cancel</button>
</div>
<div id="fade" class="black_overlay"></div>
EOD;
}
}
return $comments;
}
?>
I use the following function in order to post comments:
<?php
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$session_user_id = $_SESSION['user_id'];
$random_num = rand(0, 99999999999);
$sql = mysql_query(" INSERT INTO `comments` (comment, comment_date, user, comment_hash) VALUES ('".$comment."', now(), '$session_user_id', '$random_num') ");
return getComments();
}
?>
I use the following function in order to delete comments. Deleting comments means that I set flag=1, and in my function that displays the comments (function getComments), if flag is equal to 1 I do not display this comment:
<?php
function deletepost($comment_user_id, $comment_id){
$get_hash = mysql_query("SELECT `comment_hash` from `comments` WHERE (`user`='$comment_user_id' AND `comments_id` = '$comment_id') ");
while ($run_hash= mysql_fetch_assoc($get_hash)) {
$hash = $run_hash['comment_hash'];
}
$sql="UPDATE `comments` SET `flag`=1 WHERE (`user`='$comment_user_id' AND `comment_hash`='$hash')";
$result=mysql_query($sql) or die("Error when trying to delete...");
}
?>

My first instinct is to guess that comment_hash isn't working quite right, for whatever reason. Try simplifying your delete function:
function deletepost($comment_user_id, $comment_id){
$sql="UPDATE `comments` SET `flag`=1 WHERE (`user`='$comment_user_id' AND `comments_id`='$comment_id')";
$result=mysql_query($sql) or die("Error when trying to delete...");
}
I'm not sure why your current delete function is querying your database to grab a hash from a table and then using the hash to find the same row from the same table. It seems pointless and inefficient, and introduces more things that can break.
Incidentally, Vascowhite is correct that you shouldn't be using the old mysql library, but I don't think changing that would fix your problem here.

In deletepost why did you run while loop to get the hash , if you are deleting one comment one time . Another thing is that flag=1 happens in all your comment because hash may be common for that users all comment . You need to make hash unique for every comment of a particular user .

Related

Accessing Through PHP a Posted Javascript Variable

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

Deleting bootstrap alerts from database mysql php

So i have a notification page created using bootstrap alerts.
here's a snippet, each notification is an echo from a row of the database
<div class="container" >
<?php
$fetch = $conn->query("SELECT * FROM notifications");
while($row = $fetch->fetch_assoc()) {
$id = ''.$row["id"].'';
$notification = ''.$row["notifications"].'';
?>
<div class="alert alert-warning alert-dismissable ">
<a href="#" class="close" data-dismiss="alert" aria-label="close" id="close">
<form action='deletenotifications.php' method='post' id='myform' >
<input type='hidden' name='id' id='id' value="<?php echo $id ?>" />
<span type="submit">×</span>
</form></a>
<?php echo $notification; ?>
</div>
<?php } ?>
</div>
The user when pressing X needs to delete the notification, thus from the database too, so a hidden form containing the id of the alert to be sent to action deletenotication.php using jquery AJAX method
<script type="text/javascript">
$('#close').click(function(){
$.post(
$('#myform').attr('action'),
$('#myform :input').serializeArray(),
);
});
</script>
and here is the deletenotification.php snippet
$id = $_POST['id'];
$sqlf = $conn->query("SELECT * from notifications");
while($rown = $sqlf->fetch_assoc()){
$idbase = ''.$rown['id'].'';
if($id == $idbase){
$sql = $conn->query("DELETE FROM notifications WHERE id=$id");
}
}
it is deleting from the database but only if the alerts are closed in order, and only one alert is deleted, in order to delete the successive one, the page need to be refreshed.
closing the alerts 2, 3 and 4 wont delete the rows unless notification 1 is deleted,
I need if the user close ANY random alert to be deleted, and not in order
Thank you!
You don't need to iterate through all of the results just to delete a specific row by its ID. That costs you two queries instead of one, and the first one could potentially be costly if there are a ton of notifications in the database. Instead, you can just delete by the ID, like so.
if ( ! empty( $_POST['id'] ) && (int) $_POST['id'] ) {
$id = (int) $_POST['id'];
$conn->query("DELETE FROM notifications WHERE id=$id");
}
In the example above, I am casting the ID to an integer, for safety. But really, you should look at the database class you're using there, and instead use a prepared statement.
Aside: I noticed a couple of lines like this one with two single quotes. You don't need all of those. They are only helpful if you're concatenating. Or, if you were you defining a string literal.
$id = ''.$row["id"].'';
Instead, just assign it the value of the ID.
$id = $row['id'];
It's also a good idea to use and verify a CSRF token before responding to a request to delete a row from the database; i.e., make sure this request is a legitimate one. Maybe you're already doing this elsewhere, but I wanted to caution you in case.
See: https://en.wikipedia.org/wiki/Cross-site_request_forgery

How to not update database if $_POST value is empty?

I have been having problems with a form of an website of mine. The form values are equal to their corresponding $_POST values, which are the parameters used for updating the database.
I do not want for empty form values to be updated. However, I don't want any of the input areas to be obligatory.
That means that I would be able to update only specific content, not needing to type the values in the input areas I do not want to update. I'm having problems with this, however. Empty form values are being uploaded, so the values in the database are being changed into blank values. I've looked for tutorials in SO and over the internet, and the only (functional) ones are those which turn input boxes into obligatory. That is not how I intend it to work, so it doesn't fit.
I think the best way to do this, and I am not sure, is to change, through javaScript, the "name" attribute of the input areas into blank when the submit button is set IF the values equal empty or null. I do not know how to do this, nor do I know if this is possible, or the best way.
Here is my current code on the matter:
(first, the form an the javascript)
<script>
function validade(){
var formId = document.getElementById("configForm");
var allInputs = formId.getElementsByTagName("input");
var input, i;
for (i=0; input = allInputs[i]; i++){
if (input.value == null || input.value == "") {
input.name = "";
}
}
}
<form method="post" action="" id="configForm">
<label for="home">Home:</label>
<br>
<input type="text" id="home" name="home">
<br>
<label for="apendix">Apêndice:</label>
<br>
<input type="text" name="apendix">
<br>
<label for="about">Sobre:</label>
<br>
<input type="text" name="sobre">
<br>
<label for="contato">Contato:</label>
<br>
<input type="text" name="contato">
<br><br>
<input type="submit" value="Carregar" name="submit">
</form>
<?php require_once('editaForma.php'); ?>
(Secondly, the database query and $_POST values:)
<?php //credentials
if (isset($_POST["submit"])){
$server = 'hypotetical';
$user = 'hypotetical';
$pw = 'hypotetical';
$BD = 'hypotetical';
//estabelece a conexão
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$home = $_POST["home"];
$apendix = $_POST["apendix"];
$sobre = $_POST["sobre"];
$contato = $_POST ["contato"];
$query = "UPDATE form SET
home= '$home',
apendix= '$apendix',
sobre= '$sobre',
contato= '$contato'
WHERE id='1'";
//$query = "INSERT INTO form (home, apendix, sobre, contato) VALUES ('$home', '$apendix', '$sobre', '$contato')";
if (mysqli_query($conn, $query)){
echo "Alterações feitas com sucesso";
} else {
echo "ERRO!" . $query . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Yes, I know the DB is prone to SQL injection. I'm trying to get everything up and running first, and once all of this is set, I'll look onto security matters before the website is online.
I've been having this problem for over a week and can't figure a way out of it.
Thank you for your time and attention, in advance.
EDIT
I wish I could select two answers for the solving ones. Both of them right down led me to the solving of the problem, each helping me to see the holes in my code. As I cannot choose both, I chose the one who helped me to solve the last issues. Thank you all so much!
Build your query dynamically, by skipping empty values
$p = &$_POST; //make $p refer to $_POST
$query = "UPDATE from SET ";
if($p['home']) $query .= " home = '$p[home]' ,";
if($p['apendix']) $query .= " apendix = '$p[apendix]' ,";
if($p['sobre']) $query .= " sobre = '$p[sobre]' ,";
if($p['contato']) $query .= " concato = '$p[contato]' ,";
$query = trim($query, ','); //remove any trailing comma
$query = "WHERE id = 1";
you can then execute the query. Oh and don't forget to check that at least 1 of the variables was available. If they're all empty, don't execute.
And yeah, your code is highly vulnerable.
Glaring security holes aside, I would usually build up a string, something like this:
$home = $_POST["home"];
$apendix = $_POST["apendix"];
$sobre = $_POST["sobre"];
$contato = $_POST ["contato"];
$query = "UPDATE form SET ";
if(!empty($home)) {
$query .= "home= '$home',";
}
if(!empty($apendix)) {
$query .= "apendix= '$apendix',";
}
if(!empty($sobre)) {
$query .= "sobre= '$sobre',";
}
if(!empty($contato)) {
$query .= "contato= '$contato',";
}
// strip off any extra commas on the end
$query = rtrim($query, ',');
$query .= "WHERE id='1'";
Building the query with the comma at the end also allows you to easily add more options later if you need to.
I did it, in a simple way using NULLIF
set potato = NULLIF(potato,'')

Live changes on site

I am trying to make a php file in which I will send data from database and through them i will show 0 or 1. In my example I have a table with two user_ids and a parameter in which takes the value 0 or 1. From test.php I fill a form by giving the user_id and I submit it. When I submit it for this user the parameter in becomes 0 if it was 1 and vise versa. In next.php I use <iframe src="show.php"> and in show.php I show the user_id and in. What I want is when I submit a user_id, immediately to see the changes in show.php. What I did is to refresh the page all the time but it was too disturbing. Can you suggest something else? Here is some code.
test.php
<?php
require_once 'include_php/db.php';
global $dbcnx;
?>
<form action="" method="get">
<input type="text" name="id"/>
<input type="submit" name="submit"/>
</form>
<?php
if(isset($_GET['submit']))
{
$id = $_GET['id'];
$res = mysqli_query($dbcnx, "select * from people where uid = ".$id.";");
$row = mysqli_fetch_array($res);
if($row['in'] == 0) $up = mysqli_query($dbcnx, "UPDATE `people` SET `in`=1 WHERE uid=".$id.";");
else $up = mysqli_query($dbcnx, "UPDATE `people` SET `in`=0 WHERE uid=".$id.";");
}
show.php
<?php
require_once 'include_php/db.php';
global $dbcnx;
$res = mysqli_query($dbcnx, "select * from people");
while($row = mysqli_fetch_array($res))
{
echo $row['uid']." ".$row['in']."<br/>";
}
print "<script>window.location.replace('show.php');</script>"; //here is the disturbing refresh
next.php
<iframe src="show.php">
What you want is live updates without hard refreshing your page. You can achieve this by using AJAX requests, or by using websockets.
With an ajax request, you could easily set a timeout function to refresh your iframe every x-seconds/minutes.
This question gives a good description on how to give it a go.

AJAX to call PHP file which removes a row from database?

Alright, so I asked a question yesterday regarding how to save the blog posts that a user makes. I figured out the database side of it, and that works fine. Now, I want to REMOVE a blog post based after clicking an onclick button. Through my hours of digging through the web, I've found calling an jQuery AJAX function is the best way to go about it. I've been tooling around with it, but I can't get this working.
Blog code retrieved from database in blog.php:
$connection = mysql_connect("...", "...", "...") or die(mysql_error());
$database = mysql_select_db("...") or die(mysql_error());
$query = mysql_query("SELECT * FROM template") or die(mysql_error());
$template = mysql_fetch_array($query);
$loop = mysql_query("SELECT * FROM content ORDER BY content_id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($loop))
{
print $template['Title_Open'];
print $row['title'];
print '<button class="deletePost" onClick="deleteRow(' . $row['content_id'] . ')">Remove Post</button>';
print $template['Title_Close'];
print $template['Body_Open'];
print $row['body'];
print $template['Body_Close'];
}
mysqli_close($connection);
This creates the following HTML on home.php:
<div class="blogtitle" class="post3">Title
<button class="deletePost" onClick="deleteRow(3)">Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
Which should call my remove.js when button is clicked (This is where I start to lose what I'm doing):
$function deleteRow(id){
$.ajax({
url: "remove.php",
type: "POST",
data: {action: id}
});
return false;
};
Calling remove.php (No idea what I'm doing):
$con=mysqli_connect("...","...","...","...");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['action'];
$query = mysql_query("DELETE FROM content WHERE content_id=$id") or die(mysql_error());
My goal here is to REMOVE the row with the ID from the table which would in turn remove the blog post entirely since it won't see the row when it loops through the database table.
Any ideas?
Thanks for your help,
Kyle
couple of issues in your original code: the functions in Jquery shouldn't use a $ sign at the beginning and since you need to pass a single value I would use the query string rather than the POst, and instead of calling the "die" in php I would use the affected rows to return the callback of whether or not the value was deleted. But this is just my approach, there other ways I'm sure.
Here are little improvements in you code:
//HTML
<div class="blogtitle" class="post3">Title
<button class="deletePost" data-item="3" >Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
//JQUERY
jQuery(document).ready(function($) {
$('button.deletePost').each(function(){
var $this = $(this);
$this.click(function(){
var deleteItem = $this.attr('data-item');
$.ajax({url:'remove.php?action='+deleteItem}).done(function(data){
//colect data from response or custom code when success
});
return false;
});
});
});
//PHP
<?php
$id = $_REQUEST['action'];
$query = mysql_query('DELETE FROM content WHERE content_id="'.$id.'"');
$confirm = mysql_affected_rows() > 0 ? echo 'deleted' : echo 'not found or error';
?>
Hope this sample helps :) happy coding !
i hope this should help you i used this to remove items from my shopping cart project.
$(".deleteitem").each(function(e) {
$(this).click(function(e) {
$.post("library/deletefromcart.php",{pid:$(this).attr('prodid'), ajax:true},function(){
window.location.reload()
})
return false;
});
});

Categories

Resources