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

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']

Related

How can i run a mysql query on button click

I'm new to PHP so this might be something obvious I missed.
Im trying to make a button which increments a value in my database:
<?php
$alist = mysqli_query($conn, "SELECT * FROM `posts` ORDER BY `posts`.`id` DESC");
$results = mysqli_num_rows($alist);
if ($results > 0){
while($row = mysqli_fetch_array($alist)) {
echo $row['uid']. " says: ".$row['postText']." <button onclick=".mysqli_query($conn, "UPDATE `posts` SET `postLikes` = postLikes+1 WHERE uid = ".$row['uid'])." name='likebtn'>👍</button>".$row['postLikes']."<br>";
}
}
?>
The part that makes the button is on line 6
I just want to find how I can use the mysqli_query on button click
by the way, I already tried this: "https://stackoverflow.com/questions/3862462/php-mysql-run-query-on-button-press-click" but with no result
Thanks in advance
if your current page is called first.php,
put inside button
<button></button>
<?php
if ( isset($_GET['p']) && $_GET['p']=="like") {
do your query
}
?>
if you dont want to reload then you need ajax,
hope this was helpful. :)
You have a syntax error here
echo $row['uid']. " says: ".$row['postText']." <button onclick=".mysqli_query($conn, "UPDATE posts SET postLikes = postLikes+1 WHERE uid = ".$row['uid'])." name='likebtn'>👍</button>".$row['postLikes']."<br>";
you can either do this
$q = mysqli_query($conn, "UPDATE posts SET postLikes = postLikes+1 WHERE uid = ".$row['uid']);
echo $row['uid']. " says: ".$row['postText']." <button onclick=".$q." name='likebtn'>👍</button>".$row['postLikes']."<br>";

unable to delete record with php and ajax

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

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

Hide/Show button, also when refreshed

I am making an application that displays "activities". Each activity has his own button. When you click on that button, you add that specific activity to your "guide". The idea is that you can add one specific activity only once, so the button of that activity must disapear when it's added to the guide. I can use a simple $(this).hide() in my javascript but that obviously doesn't work when I refresh the page. So I guess i should make a check if the activity exists in de guide.
in the database I have 3 tables, 1: activity (with an ActivityID), 2: user (with a UserID) and 3: user_activity (with ActivityID and UserID, a linktable).
So the check must check if the ActivityID exists in the user_activity table, and that the UserID that belongs to that ActivityID in the user_activity table is the sames as the current users' ID.
At this moment, I know how to check the current users UserID:
//userid
$sql = "SELECT * FROM user WHERE Username = '".$_SESSION['Username']."' ";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$userid = $row['UserID'];
}
But I don't know how to check if the ActivityID already exists, and how I should make this
if else statement.
Ay the moment I use this script to display the activity (incl. the button)
$sql = "SELECT * FROM activity";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC))
{
echo '<div id="activity'.$row['ActivityID'].'">';
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['ActivityIMG'] ) . '" >', '<br>';
$instantguide = $row['ActivityID'];
echo '<input type="button" class="addActivity" onclick="MakeRequest(' . $instantguide . ')" value="Activiteit toevoegen" data-activity="' . $row['ActivityID'] . '">';
echo '</div>';
}
You need a LEFT JOIN to see what activities are already on
SELECT a.*, ua.ActivityID as added
FROM activities a LEFT JOIN user_activity ua
ON a.ActivityID=ua.ActivityID AND UserID=:userid
So you'll have an additional added field in the resultset, filled with an id if it is already chosen or empty otherwise
// First you need to get all the activityIDs from the table where you want to search and put them into an array
$sql2 = "SELECT * FROM user_activity";
$stm2 = $db->prepare($sql2);
$result2 = $stm2->execute(array());
$user_activityID = array();
while($row2 = $stm->fetch(PDO::FETCH_ASSOC))
{
// if in the table user_activity the column you are trying to compare has the same name as in activity -- $row2['ActivityID']
array_push($row2['ActivityID'], $user_activityID);
}
// Then you use in_array to compare while you go through the user_activity table
$sql = "SELECT * FROM activity";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC))
{
if (in_array($row['ActivityID'], $user_activityID))
{
// yes the current $row['ActivityID'] from the activity table, exists in the user_activity table
// you can choose whether or not to add this to your array
array_push($row['ActivityID'], $activityID);
}
}
I'm sure there's other more efficient ways to do this, using some pdo stuff that I don't know, but this is how I would have done it.

UPDATE reflected in DB but not SELECT query

First time for me here.
I am using PHP, MySQL, JavaScript and running JQUERY and AJAX functions.
I have an anchor link that runs a function.
The function emptys a DIV tag and then fills/displays (SELECT query) a table of rows in the DIV with a is null where clause. Each row has a select box where the NULL data column would go. The data in the select box comes from a different table.
When the select box changes it immediately runs the ajax to UPDATE the table row with the new data in the select box.
When you click the link to run the function again (empty, select query and display based on null column) the row that was just updated to the DB shows up again based on the is null clause. Checking the DB table at this point shows that it is in fact not null and was UPDATEd properly the first go around.
The page is never refreshed during this process and never has to be. If I do refresh it shows the proper data without the BUG.
All your thoughts are greatly appreciated.
matt
function closeItemsBtn() { // called by a click function of a standard link/button
$('#CloseItems').empty(); // remove all html from the DIV
var newAppend = '';
<?
//[... connect to db ...]
// select info from 2 different tables so it can be used in different locations if necessary
// where the row has not been reviewed and therefore is null
$query = "select * from nearmiss where reviewedId is null order by submitDate desc";
$result = $db->query($query) or die($db->error);
$query2 = "select * from hazardid where reviewedId is null order by submitDate desc";
$result2 = $db->query($query2) or die($db->error);
$num_rows = $result->num_rows;
$num_rows2 = $result2->num_rows;
// create html for the DIV tag. Creates a table in a DIV that collapses by clicking aCloseList.
// each row is in tbody so it can be striped by a all purpose striping function
// this part is the table header and opening div tags and link
$newAppend = "<p id=\"closeList\">Show/Hide {$num_rows} Near Misses requiring attention.</p><div id=\"closenearmiss\" style=\"display:none;\"><table class=\"closenearmisstable\"><tbody><tr><td>Date Submitted</td><td>Submitted By</td><td>Location</td><td>Reviewed By</td></tr><tr><td rowspan=\"2\">Type</td><td colspan=\"3\">Description / Observation</td></tr><tr><td colspan=\"3\">Action / Reinforcement</td></tr></tbody>";
// update various foreign key information from other tables
for ($i=0;$i<$num_rows;$i++) {
$row = $result->fetch_assoc();
$query3 = "select location from locations where locationId='{$row['locationId']}'";
$result3 = $db->query($query3);
$location = $result3->fetch_assoc();
$query3 = "select name from employees where employeeId='{$row['employeeId']}'";
$result3 = $db->query($query3);
$name = $result3->fetch_assoc();
// here is the table itself with the select tag in the null column name=reviewed
$newAppend .= "<tbody><tr><td>{$row['submitDate']}</td><td>{$name['name']}</td><td>{$location['location']}</td><td><form name=\"nearmissreview\" action=\"\" method=\"\"><input type=\"hidden\" name=\"docId\" value=\"{$row['nearmissId']}\"><input type=\"hidden\" name=\"type\" value=\"nearmiss\"><select name=\"reviewed\"><option>Choose name to sign off</option></select></form></td></tr><tr><td rowspan=\"2\">Near Miss</td><td colspan=\"3\">{$row['description']}</td></tr><tr><td colspan=\"3\">{$row['action']}</td></tr></tbody>";
}
$newAppend .= "</table></div>";
// this is the beginning of the second table same structure as first with collapsing but
// different data
$newAppend .= "<p id=\"closeList\">Show/Hide {$num_rows2} Hazard IDs requiring attention.</p><div id=\"closehazardid\" style=\"display:none;\"><table class=\"closehazardidtable\"><tbody><tr><td>Date Submitted</td><td>Submitted By</td><td>Location</td><td>Reviewed By</td></tr><tr><td rowspan=\"2\">Type</td><td colspan=\"3\">Description / Observation</td></tr><tr><td colspan=\"3\">Action / Reinforcement</td></tr></tbody>";
for ($i=0;$i<$num_rows2;$i++) {
$row = $result2->fetch_assoc();
$query3 = "select location from locations where locationId='{$row['locationId']}'";
$result3 = $db->query($query3);
$location = $result3->fetch_assoc();
$query3 = "select name from employees where employeeId='{$row['employeeId']}'";
$result3 = $db->query($query3);
$name = $result3->fetch_assoc();
$newAppend .= "<tbody><tr><td>{$row['submitDate']}</td><td>{$name['name']}</td><td>{$location['location']}</td><td><form name=\"hazardidreview\" action=\"\" method=\"\"><input type=\"hidden\" name=\"docId\" value=\"{$row['hazardidId']}\"><input type=\"hidden\" name=\"type\" value=\"hazardid\"><select name=\"reviewed\"><option>Choose name to sign off</option></select></form></td></tr><tr><td rowspan=\"2\">Hazard ID</td><td colspan=\"3\">{$row['description']}</td></tr><tr><td colspan=\"3\">{$row['action']}</td></tr></tbody>";
}
$newAppend .= "</table></div>";
echo "newAppend='{$newAppend}';";
$result->free();
$result2->free();
$result3->free();
$db->close();
?>
// put HTML of $newAppend php in the DIV
$('#CloseItems').append(newAppend);
// fill the select box with a variable set somewhere else in the code not displayed here
$('#CloseItems select[name=reviewed]').append(newAppendE);
stripePointsTable('.closenearmisstable tbody');
stripePointsTable('.closehazardidtable tbody');
// close list click options
$('#closeList > a').each(function() {
$(this).click(function() {
if ($(this).parent().next().css('display')=='none') {
$(this).parent().next().slideDown('slow');
} else {
$(this).parent().next().slideUp('fast');
}
});
});
// select tag change function that calls ajax and displays a message in a DIV called header
$('#closenearmiss select').change(function() {
function processDataClose(data, success) {
if (success) {
$('#header').prepend(data+"<br />");
closeItemsBtn();
} else {
$('#header').prepend(data+"<br />");
}
}
var formData = $(this).parent().serialize();
$.post('processreviewsign.php',formData,processDataClose);
});
jQuery caches your ajax calls. This is likely why you see the correct result when you refresh the page, but not in subsequent calls via ajax.
Try setting cache: false in your ajax call

Categories