Fetch random row from MySQL on click - php

I am creating a random quote generator and store the data in a MySQL database.
The code is working but it continues to fetch the same row and not a new random row everytime I click. But if I wait for say 30 seconds and click again, it works as it should. I just want it to work right away on click.
<script type="text/javascript">
$(document).ready(function() {
$(".display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(response, 5);
//alert(response);
}
});
});
});
I suspect the timeout function is not working properly as it takes longer to fetch a new row. I used the order by Rand() to get the random row. My PHP looks like this:
<?php
include("connect.php");
$finds = "SELECT * FROM citater5 ORDER BY RAND() LIMIT 1";
$result = mysql_query($finds, $con) or trigger_error(mysql_error()." ".$finds);
while($data = mysql_fetch_row($result))
{
echo "<aside class=\"citatout\">";
echo "<div id=\"paradiso\" class=\"text-vertical-center-q\">";
echo utf8_encode("<h1 class=\"animated fadeIn\" align=center>$data[0]</h1>");
echo utf8_encode("<h2 class=\"animated fadeIn\" align=center>$data[1]</h2>");
echo "</div>";
echo "</aside>";
}
?>
Why is a new row not being fetched every time?

Not quite sure if ORDER BY RAND() is working as you want it too.
- I haven't really been working with PHP for a few years, but I would probably try something like this out:
<?php
include("connect.php");
$totalrows = mysql_num_rows(mysql_query("SELECT * FROM citater5"));
$finds = "SELECT * FROM citater5 WHERE id='".rand(1,$totalrows)."'";
$result = mysql_query($finds, $con) or trigger_error(mysql_error()." ".$finds);
$data = mysql_fetch_row($result);
echo "<aside class=\"citatout\">";
echo "<div id=\"paradiso\" class=\"text-vertical-center-q\">";
echo utf8_encode("<h1 class=\"animated fadeIn\" align=center>$data[0]</h1>");
echo utf8_encode("<h2 class=\"animated fadeIn\" align=center>$data[1]</h2>");
echo "</div>";
echo "</aside>";
?>
And - as you're only getting 1 result, theres no need to run it through a while().
Hope this helps a bit.

Like the others said, rand() may not be the best to use, but I don't think it is what is causing your issue. Most likely the result is being cached if it's displaying the same result for a short period of time.
You could try turning the cache off:
$.ajaxSetup({ cache: false });
Or append the URL in the ajax call with a random number or timestamp.

Related

How to perform ajax post request to get some values from the last row of?

Hi I was asked to get some data from the last row in the database using ajax post request.
I have two files which are PHP scrip which is used to connect to the database and get all the data and convert the data to json format. I performed ajax post to PHP script to get all data. I want to modify the ajax post to request an additional data from the last row of the tables in database.
For example, in student table, there are 10 rows of data in database. I want to get data from the last row. My question is how to get values from the last row in the database..
Requirement: do not modify the SQL code as I need all the data and additionally the last row of data.
I do not want this code data[9]['student_name'];
here is my code below...
html file
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="result"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "student.php",
dataType: "json",
data: "how to request data from the last row of the database????
success: function(data){
console.log(data);
}
});
};
</script>
</body>
</html>
php script
<?php
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
?>
My question is how to get data from the last row of database?
Requirement: do not modify the SQL code as I only want to modify the ajax post. Please help me. This is for my project.
Change the PHP code as follows.
<?php
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
$limit = count($json_array);
echo json_encode($json_array[$limit-1]);
?>
Your question is a bit unclear. It seems you want to send a param to PHP the only the last row, but I'm not sure. If that's true, you can do what #Rossi proposed adding a parameter like:
data: {
lastOnly: true
}
And at the end of the script:
if (!isset($_POST["lastOnly"])) {
echo json_encode($json_array);
} else {
echo json_encode($json_array[count($json_array)-1]);
}
But, if still wants to get all data from back-end but deal with the last row in your javascript, you can do what i've said in the comments:
success: function(data) {
var lastRow = data[data.length - 1];
}
UPDATE: To get only one field.
You can send back only one value and your data will receive a string instead of a json object:
echo $json_array["student_name"];
You can get the the property from your json object:
data.student_name

Notifications system getting all new records

So I've built all of the basic functionality, but with a major flaw. I search from the last id inserted which is fine.. But the error is when I get to the PHP. I search for MAX id and it sends back the last record obviously.. But if a user does three actions that sends a notification to you, then the other two don't show via the call, only when the page refreshes.
So what would I have to change to get all the notifications from the database when each call is made from the last id it searches for in the front end? I presume maybe a while loop in the PHP page rather than the max id. but then how would the back end select ALL new data from the front ends last max id?
So this is what I have.
<?
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select MAX(notification_id) AS notification_id ,notification_status,notification_targetuser,notification_triggeredby,notification_throughurl from notifications WHERE notification_targetuser='$user1_id' AND notification_status=1 ORDER BY notification_id DESC LIMIT 1";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id']?>";
var notification_targetuser="<?php echo $notification['notification_targetuser']?>";
var notification_triggeredby="<?php echo $notification['notification_triggeredby']?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&notification_targetuser="+notification_targetuser+"&notification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
if(data.notification_id>notification_id){
$("#notif_ui"+notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-" class="notif_actual_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br/></div></div></div><hr/>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
if(!data.notification_id.length) {
//no results...
return;
}
notification_id = data.notification_id;
}
}
});
}
setInterval(loadIt, 10000);
</script>
PHP
$json = array();
$com=mysqli_query($mysqli,"select MAX(notification_id) AS notification_id,notification_content,notification_time,notification_triggeredby,notification_throughurl from notifications where notification_id > '$id' AND notification_targetuser=".$_GET['notification_targetuser']." AND notification_triggeredby=".$_GET['notification_triggeredby']." AND notification_status=1");
$num = mysqli_num_rows($com);
if($num>0){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
$json['notification_content'] = $resultArr['notification_content'];
$json['notification_throughurl'] = $resultArr['notification_throughurl'];
$json['notification_triggeredby'] = $resultArr['notification_triggeredby'];
$json['notification_time'] = $resultArr['notification_time'];
mysqli_free_result($com);
echo json_encode($json);
}
I in fact used mysqli_free_result($com);within the while loop preventing more than one set of results returning and therefore removed this from the query.

MySQL Search Operators and "LIKE"

I'm having a strange issue where using the % operator isn't grabbing the right database entries for my autocomplete bar.
Here is a sample of my database structure:
Here is what happens when I search the letter 'g' in my search bar. Note that I have the query echoed at the bottom of the div so you can see the correct thing is being searched:
Then here is what happens when I add an 'a' after the g. You would expect the entry to remain there, as the entry's name is "aattaagataca", and it contains a ga, flanked by some other characters.
On another note, the search of the letter 'g' didn't return the '5gooper' entry. Any ideas as to why this might be happening? I will post my sample code, but please don't making comments about sql security cause I'm just coding the raw stuff for now. Also don't redirect me to jQuery UI's autocomplete because I'm not looking to use that.
PHP
$searchquery = $_POST['searchquery'];
$searchquery2 = "%$searchquery%";
$query = "SELECT id, name, author, date FROM data WHERE name LIKE '$searchquery2' ORDER BY DATE DESC LIMIT 20";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result);
while ($row = $result->fetch_assoc()) {
echo "<a href=\"preview.php?id=$row[id]\"><div class=\"searchResult\">";
echo $row["name"];
echo "<br/>";
echo "<b>Author: </b>";
echo $row["author"];
echo "<br/>";
echo "<b>Date: </b>";
echo $row["date"];
echo "</div></a>";
echo "<hr>";
}
print_r ($row);
echo "$searchquery2";
JS/jQUERY
$('#sbar').keyup(function(){
var query = $(this).val();
$.ajax
({
url: "autocomplete.php",
data: {searchquery: query},
type: 'POST',
success: function(data){
$('#acd').html(data); //acd stands for auto complete div
}
});
});
Basically my query is just very inconsistent with what it returns. When I query my SQL database directly (through phpMyAdmin, it indeed returns the correct entries. For example, a query such as:
"SELECT * FROM data WHERE name LIKE '%g%' ORDER BY DATE DESC LIMIT 20"
Returns both entries which contain 'g' (gooper and gataca).
*****EDIT*****
Here is the result of typing 'g' and doing print_r ($row);
simply remove the following line
"$row = mysqli_fetch_array($result);" from your code and you should be fine. Your application has already retrieved the first record before entering the while-loop. That's why you only get a single record while searching for %g% and no record while searching for %ga%

not able to handling ajax request from a small chat module

i am developing a simple chat module for my client, but not able to handle loop from setInterval()
Here is the js code from which i sending the request to get the data from the database
function getData(){
jQuery.ajax({
url: '../../get_data.php',
data: 'to=<?php echo $_SESSION['ch_usr_id']; ?>',
cache: false,
success: function(data){
jQuery('<div>'+data+'</div>').appendTo("#ch-data-con");
setInterval("getData()", 5000);
}
});
}
and here is the get_data.php file which produce the data according to request
require "../../support/connection/connect_gib.php";
$to = addslashes(trim($_REQUEST['to']));
$query = "select * from chat where
guest_id='".mysql_real_escape_string($to)."' order by id asc";
$result = mysql_query($query);
while( $row = mysql_fetch_assoc($result) ){
echo "<b>".$row['frm']." : </b> " .$row['message'] . "<br />";
}
i got the result in loop like all the data repeat again and again, but i want the newly updated data, please make me correct what i did wrong..
You are using appendTo function in jQuery.. So all chat messages will be appended after old list. You can use .html() function to replace complete data.
Another way is to get only last chat message from php side, so all data will not be repeated. You can use auto id to point which messages are fetched last.
You should preserve the last id fetched and use that for new request. And on server side you should fetch from there.
$id= addslashes(trim($_REQUEST['id']));
$query = "select * from chat where
guest_id='".mysql_real_escape_string($to)."' AND id > '".mysql_real_escape_string($id)."' order by id asc";
function getData(){
jQuery.ajax({
url: '../../get_data.php',
data: 'to=<?php echo $_SESSION['ch_usr_id']; ?>&id=' + last_id_fecthed,
cache: false,
success: function(data){
jQuery('<div>'+data+'</div>').appendTo("#ch-data-con");
setInterval("getData()", 5000);
}
});
}

jQuery looping only works on last row

I am trying to show the results of the status of a bidding item using jQuery every second on every row in MySQL table, however only the result of the last row of the table is returned.
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
?>
<script type=text/javascript>
function updatestatus(itemnum)
{
var url="updatestatus.php?auc=<?php echo $row['item_id']; ?>";
jQuery('#status' + itemnum).load(url);
}
setInterval("updatestatus(<? echo $z?>)", 1000);
</script>
<?
$z++;
}
?>
When I view source in the browser, the values for #status and auc for every row are correct. What am I missing here?
Here's the code for updatestatus.php
<?php
session_start();
require_once("connect.php");
$id = $_GET['auc'];
$getstatus = mysql_query("SELECT status FROM items WHERE item_id = '$id' ");
$row = mysql_fetch_array($getstatus);
echo"$row[status]";
?>
Everything looks good, save for the fact that it looks like you're creating multiple references to your updatestatus() function.
In Javascript, if you create multiple functions with the same name, calling them will only result in one of them running, usually the first or last one (depending on the implementation), so all the code you need to run in those functions needs to sit together in one function body.
If you're determined to use the code you've created, you'd need to throw all those update calls into one function body. There would be better ways to achieve what you need, but doing it with the code you've created, this would probably work better:
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$javascript = "";
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
// build the javascript to be put in the function later over here...
$javascript .= "jQuery('#status". $z ."').load('updatestatus.php?auc=". $row['item_id'] ."');";
$z++;
}
?>
...and then further down the page, create the javascript (modified slightly):
<script type=text/javascript>
function updatestatus()
{
<?php echo $javascript; ?>
}
setInterval(updatestatus, 1000);
</script>
So you're basically building up the Javascript that you'll need in your function, echoing it out inside the function body, and then setting the interval will call all that code, in this case, every second.
Like I said, there are definitely more efficient ways to achieve what you're trying to do, but this should work fine for now. I hope this makes sense, but please let me know if you need any clarity on anything! :)
I don't see that you're populating data using a incrementor. Is this supposed to be adding content to a page or replacing the content? from what it looks like it will just display one item, and then replace that one item with the next until it's done, which is why you see only the last row.
OR ...
the jquery update isn't being fed the $i variable .. change the function to
function updatestatus(itemnum) {
and then jquery echo to jQuery('#status' + itemnum).load(url);
then you can add the on-click/ or whatever to include the number
onclick='updatestatus("1")'
on the other hand you might be needing to pass the total number of items to the function and then creating an if there to cycle through them (not tested, but you get the idea i hope)
function updatestatus(numitems) {
var url = "";
var itemID = "";
for (i = 1; i <= numitems; i++) {
itemid = getElementById('#status'+numitems).getAttribute("itemID")
url="updatestatus.php?auc="+itemID;
jQuery('#status'+numitems).load(url);
}
}
setInterval("updatestatus()", 1000);
and the html element for "#status1" as created by the PHP should look like this:
<div id="status1" itemid="23455">
</div>

Categories