Deleting bootstrap alerts from database mysql php - javascript

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

Related

Delete specific entry from database by clicking on it

I'm building a web App for a friend, this is my first async site and I'm learning lots of cool stuff, but there are some details that make me struggle.
This is the general idea:
This simple app gets specific tables from a database using PHP and jQuery and shows them asynchronously on the page. There's this specific table (a waitlist) that shows all atributes from all entries on the table plus a small button that SHOULD delete that specific entry, the PHP code for the creation of the table is as follows:
<?php
include("con.php");
$result = mysqli_query($c,"SELECT * FROM waitlist");
echo "<thead>";
echo "<tr>";
echo "<th>Nombre</th><th>Sillas</th><th>Hora de Llegada</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID'] . ' id="deleteWaitlist">X</button>
</td>';
echo "</tr>";
}
echo "</tbody>";
mysqli_free_result($result);
?>
This is the table schema:
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL,
PRIMARY KEY(ID)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the best way of having the button delete the entry it apears on? The function refreshes the table every few seconds so deleting it from the database is all I need. I also have an incomplete PHP function that gets called on buttonpress that shold delete the entry, but Im unsure as to how to complete it. Here it is:
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
I need to replace the $_POST[name] with an identifier for the row, this is my problem. What's the best way of doing this? Can I pass it somehow though the jquery.ajax() call? Do I need a new table attribute ID? I'm sure the "this" keyword can be used somewhere. Is PHP and ajax even the best way of doing it?
Ajax writes the table on "#result_table", here's the relevant code if it's needed:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
</div>
EDIT: I updated the code as recomended by #vnponce
This is the code for the ajax call:
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
console.log(result);
}
});
});
After fiddling with the code I got rid of all errors and updated the post, but the entries are still not getting deleted.
The best way is creating an ID identifier in your table, then this identifier can be added in your 'Delete' button.
The button trigger a function that send ID, and your PHP file recive it and delete de data comparing the ID.
The identifier can be added in table schema ( i don't know if it is the rigth code, I always made in phpMyAdmin )
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL
);
First add the ID in delete photo.
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID']. ' "id="deleteWaitlist">X</button>
</td>';
The ajax
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({url: "YOUR_PHP_FILE.php", {id: i}, success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
// console.log(result);
}});
});
Now your PHP with ID
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
Well I hope help. If i have an error or you have a question let me know.
UPDATE*
Maybe there's an error deleteWaitlist.php , you can return error if it exist.
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
if ( ! mysqli_query($c,$sql) )
{
return "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

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.

Trying to show full size image from thumbnails retrieved using php and database

I'm trying to use thumbnails retrieved from database. PHP is working fine and displaying my thumbnails. I don't know how to get the id from database into the imageID for JavaScript function and getElementById, to display as full size when clicked. I can do straight JavaScript inline onsubmit in my code. The inline JavaScript is working; the thumbnail is being displayed, and when clicked a full size shows, but I want to use my database retrieved images to show the full size image when clicked. Do you think you can help me with my code?
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script type="text/javascript">
//function that shows full sized image of the thumbnail
function showImage(imageID) {
//first hide all images
document.getElementById('image1').style.display = 'none';
//then display the one that had its thumbnail clicked.
document.getElementById(imageID).style.display = '';
}
</script>
</head>
<body>
<h1></h1>
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "travel1";
$conn = new mysqli($host, $user, $pass, $database);
if ($conn->connect_error)
die ("Unable to connect to database: " . $conn->connect_error );
$sql = "select * from what_to_do
where DESTINATION='NEW YORK CITY'";
$result = $conn->query($sql);
if ($result->num_rows >= 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<td>".$row["THUMBNAIL"]."</td>";
}
echo "</table>";
}
else {
echo "You have no destinations";
}
$conn->close();
?>
<p>
<img id="image1" alt="" src="images/NewYork/Pick7/9-11show.jpg"
style="display: none" />
</p>
<p>
<img alt="" src="="images/NewYork/Pick7/9-11thumb.JPG"style="width:100px;
height:100px" onclick="showImage('image1')" />
</p>
In this code the second img tag is closed prematurely, like src="something" etc etc. If that tag were properly formed, I think this should work?
Otherwise, you would just do something like " src="/blah" />
Hopefully that answers your question?
And then for the I onclick function just do essentially the same thing.
I'm going to presume a lot, but here goes!
The above answer is correct, you are prematurely closing an image tag at the bottom of your code, it should be like this:
<img alt="" src="images/NewYork/Pick7/9-11thumb.JPG" style="width:100px;
height:100px;" onclick="showImage('image1')" />
But otherwise there are a few other issues to address...
First, by typing in the specific name of the destination for each query on every page you'll be defeating the purpose in using a database! Just like you've mentioned, you need to use the ID and pull in the data accordingly.
To do this you need to define what the ID is by letting the user select the destination on a previous page/section(in your example a destination list might be appropriate with all the destinations in some kind of order, be that ascending or descending ect... PHP has a few different ways.)
So first, the query to sort by ID is:
SELECT * FROM travel1 order by id desc
and then to set the ID in the URL when the destination link is clicked, here's an example link using php to carry the ID to the next page:
more info
Once you get to the destination info page(that's what I'm calling your above code), filter your data so that you can access the specific destination by ID by firstly adding this to your page(after you've connected to the database that is):
<?php
if(isset($_GET['id'])){
$id = preg_replace('#[^0-9]#i', '',$_GET['id']);
$result = $con->query("SELECT * FROM travel1 WHERE id='$id' ");
while($rows = $result->fetch_assoc()) {
echo "<td>".$row["THUMBNAIL"]."</td>";
}
} else {
echo "We're having some issues...";
}
?>
The above code will pick up the database ID from your URL which was carried over from the previous page(your new destination list) and can be echoed out like your other links such as:
'echo "<td>".$row["THUMBNAIL"]."</td>";'
I hope this helped! =D

delete a certain comment in comment-reply system in php

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 .

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