unable to delete record with php and ajax - php

I'm just trying to delete a record by its row id from a table using php and ajax but when I click on the button it neither shows error nor performs the action.
here is my delete.php code:
<?php
session_start();
include 'db.php';
if(isset($_GET['name'])){
$user = $_GET['name'];
$query = mysqli_query($con, "SELECT * FROM login WHERE username='$user'") or die (mysqli_error());
$result = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query)){
$_SESSION['user'] = $row['username'];
}
}
$query = mysqli_query($con, "SELECT * FROM pm WHERE touser = '".$_SESSION['user']."' ORDER BY pmdate DESC" ) or die (mysqli_error());
$result = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query)){
$id = $row['id'];
$delquery = mysqli_query($con, "DELETE * FROM pm WHERE id ='$id'") or die (mysqli_error());
$delresult = mysqli_num_rows($delquery);
}
?>
and here is the ajax and delete code of html
<script>
$("#delete").click(function() {
$.ajax({
type: "POST",
url: "delete.php",
success: function(response){
$("#messages").html(response);
}
});
});
</script>
<div id="messages"></div>
any one have any ideas?

Change you query
-> your "DELETE * FROM pm WHERE id ='$id'"
-> correct "DELETE FROM pm WHERE id ='$id'"
You send POST method true AJAX and in php code you write GET, change it.

you set -> type: "POST" and use a GET method in your link
you then use -> $user = $_GET['name'];
+ did you try to echo GET / POST vars before you query and echo your query ?
+ I guess you send nothing to your page...
+ don't use * in DELETE query

You have few issues in your code.
1. you are not sending any parameters to the delete.php page. Please send the record ID to the delete.php page
2. remove * from DELETE query
3. you are adding PHP variables in HTML anchor tag without using PHP tags. you need to correct the link
4. you need to add event.preventDefault() inside your function

Related

How to only fetch only the new row from MySql automatically?

I am making a messaging service for my users. I used AJAX for sending the message without refreshing the message. I want to fetch the new row from the database automatically (if the current user or the other side user enters any message), without refreshing the older messages.
<div id="readmsg">
#The messages is to be read here....
</div>
<textarea placeholder="Write your message.." id="msg"></textarea>
<input type="submit" value="Send" id="sendmsg">
<?php $user1 = 1; $user2 = 2; ?>
<script type="text/javascript">
$(document).ready(function(){
$("#sendmsg").on("click",function(e){
e.preventDefault();
var usera = <?php echo $user1.";";?>
var userb = <?php echo $user2.";";?>
var msg = $("#msg").val();
$.ajax({
url : "sendmessageprocess.php",
type : "POST",
data : {message:msg, user1:usera, user2:userb},
success : function(data){
document.getElementById("msg").value="";
$("#msg").val("");
}
});
})
});
</script>
As I see in comments the friends only complicated your problem and be far from your main problem
as a chatroom creator in past, I will seriously offer you to use another technologies instead of ajax
But if it's necessary to use ajax, the best way for solving your problem is:
after fetching new messages in your query, put the last row id in a some index in sessions or cookies such as:
$_SESSION['last_msg_id'] = $row['id'];
and in another requests get the messages that their ids is more than your last_msg_id
$query = 'SELECT * FROM `messages` WHERE `id` > "' . $_SESSION['last_msg_id'] . '"';
and, for new clients that haven't your session index get last 10 messages for example and create your session index by the told way. example:
if(isset($_SESSION['last_msg_id'])){
$query = 'SELECT * FROM `messages` WHERE `id` > "' . $_SESSION['last_msg_id'] . '"';
}else{
$query = 'SELECT * FROM `messages` ORDER BY `id` ASC LIMIT 10';
}
// your query process
$rows = {your rows};
foreach($rows as $row){
$_SESSION['last_msg_id'] = $row['id'];
}
// or
$rows = {your rows};
$last_row = end($row);
$_SESSION['last_msg_id'] = $last_row['id']

How to add item/post to favourites

I'm trying to create a button which will allow users to favourite certain posts using php and jquery (ajax). I've been trying to use This answer on here to get it all working, but I'm having trouble with getting the post id specific to the post that is meant to be favourited and instead it always gives the post id of the last post to be loaded on the page. Here's my code as it is, but I suspect I've probably just made a mistake in adapting it.
I have 3 tables; Users, Posts and Favourites. In Users I have username password and id, Posts I have id (and content) and in Favourites I have id, userid and postid.
Jquery:
<script>
$(document).ready(function() {
$('.favourite').on('click', null, function() {
var _this = $(this);
var postid = _this.data('$postid');
$.ajax({
type : 'POST',
url : '/add.php',
dataType : 'json',
data : '$postid='+ postid,
complete : function(data) {
if(_this.siblings('.favourite'))
{
_this.html('<img src="add2.png" />');
}
else
{
_this.html('<img src="add1.png />');
}
}
});
});
});
</script>
Main PHP (index.php):
<?php
$getposts = mysql_query("SELECT * FROM Posts ORDER BY id DESC") or die(mysql_query());
while ($row = mysql_fetch_assoc($getposts))
{
$id = $row['id'];
$user = $_SESSION['user'];
$findid = mysql_query("select * from Users where username='$user'");
if ($rows = mysql_fetch_assoc($findid));
{
$userid= $rows['id'];
$postid= $id;
}
echo '<img src="add1.png" />';
}
?>
(There is other code, but it's not related to this section.)
add.php:
<?php
session_start();
require_once('connect.php');
$userid = $_SESSION['$id'];
$postid = $_SESSION['$postid'];
$query_favorite = "SELECT userid, postid FROM Favourites";
$favorite = mysql_query($query_favorite) or die(mysql_error());
$row_favorite = mysql_fetch_assoc($favorite);
$totalRows_favorite = mysql_num_rows($favorite);
if(in_array($_POST['id'], $row_favorite))
{
$Del="DELETE FROM Favourites WHERE userid='$userid' AND postid='$postid'";
$result = mysql_query($Del);
}
else
{
$Add = "INSERT INTO Favourites (userid, postid) VALUES ('$userid', '$postid')";
$result = mysql_query($Add);
}
?>
Thanks in advance for any assistance!
In main.php you are using data-id="' . $postid . '".
Which inserts the postId into the HTML, right?
But in your Javascript you are trying to fetch this data element with
var postid = _this.data('$postid');
data : '$postid='+ postid,
instead of
var post_id = _this.data('id');
data : 'id='+ post_id,
Because your data attribute isn't data-$postid, but data-id.
Same error in add.php:
$userid = $_SESSION['$id'];
$postid = $_SESSION['$postid'];
without single-qoutes:
$userid = $_SESSION[$id];
$postid = $_SESSION[$postid];
Because, when you single-quote the variable, then its the string "$id",
which isn't in $_SESSION.
and you have to fetch $id(postid) from the $_POST data send with your AJAX request. The code missing is: json_decode incoming POST and grab the id, then use it...
Debugging hints:
test that the data is inserted into HTML
add var_dump($_POST); to add.php in order to see the data the AJAX requests posts. The "id" should be part of it.
json_decode() the incoming $_POST to get the ID
and then use it on other variables

deleting records from mysql table

Continuing with my simple CRUD, I'm stuck again...
So I have a table created called "usuaris" and a column called "id" which is my auto-increment and then another column called "usuari_nom". Now, I want to add "delete function", so when I am displaying the records of my table I've added a to delete it:
<div id="main">
<?php
global $conn;
$query = "SELECT * FROM usuaris";
if($grup_usuaris = mysqli_query($conn, $query)) {
echo "<table>";
echo "<tr><th>Usuaris</th><th>Accions</th></tr>";
while($row = mysqli_fetch_assoc($grup_usuaris)) {
echo "<tr><td>" . $row['usuari_nom'] . "</td><td>Eliminar usuari</td></tr>";
}
echo "</table>";
echo "+ Afegeix Usuari";
mysqli_free_result($grup_usuaris);
} else {
echo "query failed";
echo("Error description: " . mysqli_error($conn));
}
?>
</div>
So now, If I click on "eliminar usuari" it goes to the file where I am adding the query to delete, plus the id of that user; for example: "http://localhost/calendario/elimina_usuari.php?subject=6". But then, in the file elimina_usuari.php, how do I select the id to know what record to delete?
I've thought with $_GET but it doesn't seems to work, either with $_POST:
elimina_usuari.php
<?php
global $conn;
$usuari_id = $_GET['id'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
Any clue how can I get its id? Should I take it from the url somehow?
Thanks
you're doing fine.
just need to change this
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
as you're setting subject instead of id in your url
http://localhost/calendario/elimina_usuari.php?subject=6
^
and if you want to process id, like $_GET['id'], you need to change URL.
"http://localhost/calendario/elimina_usuari.php?id=6"
^ change here
EDIT
as per your comment,
you can use any $variable to $_POST or $_GET, it has nothing to do with the database column name.
Like you can use following.
"http://localhost/calendario/elimina_usuari.php?eve_mf=6"
and on elimina_usuari.php page,
$id = $_GET['eve_mf'];
and second part, why can I do that and I don't need to call it id as it is called in my db table?
Again, it's not the issue what you call variables in you local environment, all you to do(and should take care of) is to put right parameters in your sql query.
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
Here id is the name of your column name in your database. You can't change it here if you even want it to.
however, $usuari_id is your local variable, and you can change it whatever you want.
Hope I've explained what you're looking for :)
You can get the id with $_GET['subject'].
Please be aware about SQL injection as you are wrongly get the id of the user to be deleted:
$usuari_id = mysqli_real_escape_string($conn, $_GET['subject']);
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
You just need to Get the exact variable name or parameter name which you have sent with your url
I mean see your url contains subject=6
that means you have to get subject instead of id;
please replace this code
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
try this in elimina_usurai.php
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

Fetching data in an AJAX-page

In my AJAX-page I want to fetch data from a database. In my first page I have del image to delete a record. I passed the file cid as 'rmvfile' to the next page and fetched and displayed them on the 2nd page.
In my first page I pass cf_id:
<img src="image/delete1.png" alt="delete" style="width:10px;height:10px" title="Remove" onclick="myFunction('.$fet['cf_id'].');">
function myFunction(cid) {
var rmvfile=cid;
if (confirm("Are you sure you want to Delete the file?") == true) {
if(cid!='') {
$.ajax({
type: 'post',
url: 'delete_cli_file.php',
data: {rmvfile: rmvfile},
});
}
}
}
I my 2nd page I use:
<?php
include "config.php";
$s = $_POST['rmvfile'];
$sel = "select cf_id from client_file where cf_id='".$_POST['rmvfile']."'";
$sel1 = mysql_query($sel);
$sfet = mysql_fetch_assoc($sel1);
$file_name = $sfet['file_name']; //not fetched
$echeck = "delete from client_file where cf_id='".$_POST['rmvfile']."'";
$echk = mysql_query($echeck);
$del = "delete from client_file where file_name = '$file_name' ";
$del1 = mysql_query($del);
?>
$echeck = "delete from client_file where cf_id = '".$_POST['rmvfile']."'";
and $sel="select cf_id from client_file where cf_id='".$_POST['rmvfile']."'"; are working.
My problem is that the value is not fetched in $sfet['file_name'].
try
$del1 = mysql_query( $del ).mysql_error();
You are not fetching file_name from mysql query
$sel = "select cf_id from client_file where cf_id='".$_POST['rmvfile']."'";
Change query to fetch file_name
$sel = "select cf_id,file_name from client_file where cf_id='".$_POST['rmvfile']."'";
Please correct the sql query section in your code
currently it is
$sel = "select cf_id from client_file where cf_id='".$_POST['rmvfile']."'";
it should be
$sel = "select * from client_file where cf_id='".$_POST['rmvfile']."'";
As now it is fetching only cf_id, you didn't get the other fields.
In your 2nd page
if($sel1=mysql_query($sel)) //Wrong verification
Use == rather than =
if($sel1==mysql_query($sel))
Change your sql query to this
$myvar= $_POST['rmvfile'];
$sel="select cf_id from client_file where cf_id='$myvar'";
$sel1=mysql_query($sel);
$sfet=mysql_fetch_assoc($sel1);
$file_name=$sfet['file_name'];
You have not closed your image-tag properly and the quotes are not closed as well
<img src="image/delete1.png" alt="delete" style="width:10px;height:10px"
title="Remove" onclick="myFunction('.$fet['cf_id'].');">
And as stated by manikiran, check the if.condition.

Refresh database rows & display without reloading page

I need to update database rows and display the change without reloading the page.
This is what I use currently to display the information:
<?php
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = "SELECT * FROM craffyposts ORDER by time DESC $limit";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['like']; // This is what needs to be changed when database is updated.
?>
<?php
};
?>
like.php:
<?php
$cid = $_GET['id'];
database_connect();
$query2 = "SELECT * FROM craffyposts WHERE id = '".$cid."'";
$result2 = mysql_query($query2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($result2)) {
$lk = $row2['like'];
};
$nlk = $lk + "1";
mysql_query("UPDATE craffyposts SET `like` = '".$nlk."' WHERE id = '".$cid."'") or die(mysql_error());
echo "<script type='text/javascript'>window.location='index.php';</script>";
?>
Any help?
Without reloading the page? You'll have to use a client-side request to fetch new data from the server. the most common of such would be JavaScript's AJAX. You can use AJAX to fetch data from the server (presumably in some quickly parsed format such as JSON) and then load the data into the page with JavaScript.
use JavaScript (or a JS Framework, I prefer jQuery) and use Ajax-Methods to display the data.

Categories