PHP: Check mysql database every 10 seconds for any new rows - php

I am making a php chat and am starting the php checking database part. So when a user types something into the chat, it gets recorded in the MySQL database, how would I check the database every 10 seconds so that one user's chat would update with new messages from other users. I know that you can use an ajax request to a page with an interval, but I want the php to be on the same page, instead of having to use numerous pages. This is the code for checking the database
<?php
$con = mysqli_connect('host','user','pass','database');
$query = mysqli_query($con,"SELECT * FROM `messages`");
while ($row=mysqli_fetch_assoc($query)) {
$user = $row['user'];
$message = $row['message'];
echo 'User: ',$user,' Message: ',$message;
}
?>
Thanks in advance anyone!

Use MySQL Event Scheduler.
Below link will guide you through .
http://www.9lessons.info/2012/10/mysql-event-scheduler.html.
I think best option in your case .

AJAX is probably the simplest solution. You can perform an AJAX request on the same page your PHP code is executing on if you really want to.
(function check() {
$.get('mypage.php', function(data) {
doSomethingWith(data);
setTimeout(check, 5000); // every 5 seconds
});
})();

PHP doesn't have a setInterval function. While I'm sure you can use a crontask to automate it on the server, you can also achieve this with some simple Javascript.
The concept you are trying to achieve is known as Short Polling. What you want to do is to have a setInterval function in Javascript that constantly makes AJAX requests to your PHP file which performs the check to the database for new messages. Your PHP should return that information to your script where you can then simply populate the user's screen.
There is also Long Polling where you simply maintain the connection and have a setTimeout to wait for messages to come in. You can find more information yourself and if you have questions, you can come back here.
A good video about this:
https://www.youtube.com/watch?v=wHmSqFor1HU
Hope this helps.

This is what you need. We need set time for ajax auto reload. Don't put everything in one page. Because you must reload page to refresh data. That is bad solution.
Call jQuery Ajax Request Each X Minutes

Make a while for 30 seconds, and check the db every second, once you find a record the while is being broken, also it is being broken when 30 secs are expired.
$sec = 1;
while($sec <= 30) {
if(has record)
Send to the user;
$sec++;
sleep(one sec here);
}
Use sleep for 10 secs in order to check every 10 secs...

Related

"Live notifications" feaure

I want to add "live notifications" feature for my users: When they receive a new message(via the chat system) then display a notification badge on the chat icon in the navbar.
I was thinking to do: AJAX calls with setInterval:(As seen on another post here)
The AJAX call:
setInterval('checkUpdates', 2000);
function checkUpdates() {
$.get('/check_updates.php?timestamp=' . lastTime, function (results){
// do stuff here
}
);
The PHP code:
$timestamp = $_REQUEST['timestamp'];
$results = query('SELECT message FROM messages WHERE messageTime > "$timestamp"');
echo fetch($results);
I have a few questions before:
1) Since I want the update-checking to be constantly running, and the navbar is always present (always on the top of the page), is the navbar.php file the correct place to put that AJAX call?
2) How badly does that affect performance of the website, to have AJAX calls constantly running every 2 seconds?
3) Is there a better way? Do websites like Facebook have an efficient way to immediately popup the chat window whenever you get a new message, or it's thanks to their huge amount of servers?
Thanks

Long polling - Message system

I'm looking into doing some long polling with jQuery and PHP for a message system. I'm curious to know the best/most efficient way to achieve this. I'm basing is off this Simple Long Polling Example.
If a user is sitting on the inbox page, I want to pull in any new messages. One idea that I've seen is adding a last_checked column to the message table. The PHP script would look something like this:
query to check for all null `last_checked` messages
if there are any...
while(...) {
add data to array
update `last_checked` column to current time
}
send data back
I like this idea but I'm wondering what others think of it. Is this an ideal way to approach this? Any information will be helpful!
To add, there are no set number of uses that could be on the site so I'm looking for an efficient way to do it.
Yes the way that you describe it is how the Long Polling Method is working generally.
Your sample code is a little vague, so i would like to add that you should do a sleep() for a small amount of time inside the while loop and each time compare the last_checked time (which is stored on server side) and the current time (which is what is sent from the client's side).
Something like this:
$current = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$last_checked = getLastCheckedTime(); //returns the last time db accessed
while( $last_checked <= $current) {
usleep(100000);
$last_checked = getLastCheckedTime();
}
$response = array();
$response['latestData'] = getLatestData() //fetches all the data you want based on time
$response['timestamp'] = $last_checked;
echo json_encode($response);
And at your client's side JS you would have this:
function longPolling(){
$.ajax({
type : 'Get',
url : 'data.php?timestamp=' + timestamp,
async : true,
cache : false,
success : function(data) {
var jsonData = eval('(' + data + ')');
//do something with the data, eg display them
timestamp = jsonData['timestamp'];
setTimeout('longPolling()', 1000);
},
error : function(XMLHttpRequest, textstatus, error) {
alert(error);
setTimeout('longPolling()', 15000);
}
});
}
Instead of adding new column as last_checked you can add as last_checked_time. So that you can get the data from last_checked_time to the current_time.
(i.e) DATA BETWEEN `last_checked_time` AND `current_time`
If you only have one user, that's fine. If you don't, you'll run into complications. You'll also run one hell of a lot of SELECT queries by doing this.
I've been firmly convinced for a while that PHP and long polling just do not work natively due to PHP not having any cross-client event-driven possibilities. This means you'll need to check your database every second/2s/5s instead of relying on events.
If you still want to do this, however, I would make your messaging system write a file [nameofuser].txt in a directory whenever the user has a message, and check for message existence using this trigger. If the file exists and is not empty, fire off the request to get the message, process, feed back and then delete the text file. This will reduce your SQL overhead, while (if you're not careful) increasing your disk IO.
Structure-wise, an associative table is by far the best. Make a new table dedicated to checking the status, with three columns: user_id message_id read_at. The usage should be obvious. Any combination not in there is unread.
Instead of creating a column named last_checked, you could create a column called: checked.
If you save all messages in the database, you could update the field in the database. Example:
User 1 sends User 2 a message.
PHP receives the message using the long-polling system and saves the message in a table.
User 2, when online, would send a signal to the server, notifying the server that User 1 is ready to receive messages
The server checks the table for all messages that are not 'checked' and returns them.

Get last load/refresh time of webpage in PHP

I'd like get the time when the actual webpage has been loaded or refreshed.
I've tried http request but there is no such information.
After page is loaded ajax function checks new messages every 60 seconds. I need to show only new ones (the ones that have been posted after the page load).
Thanks a lot in advance.
Timestamp every message. In your AJAX function, send a parameter of the last message you already have. Return only messages newer than that. E.g., the AJAX URL you hit can look something like /get_messages.php?newer_than=1343041382.
As #DaveRandom mentioned:
You just need to store the result of time() in $_SESSION - e.g. $_SESSION['lastPoll'] = time();. Then every time you poll the server for new messages "SELECT * FROM messages WHERE message_time > ".$_SESSION['lastPoll'], and update the stored value with the new time()
Assuming you store the time the message was sent in the database, and that you store it as a timestamp, you could use something like this:
When the page is loaded, you could save the current time as this:
$page_load_time = time();
Then just send the $page_load_time to your file that is loaded with AJAX, using post or get, and then in the PHP-file loaded with AJAX, you could do an SQL-query that gets all the new messages. Maybe something like this:
$sql = "SELECT * FROM `messages` WHERE `time` > '{$page_load_time}'

PHP: Most efficient way to make multiple fsockopen(); connections?

Hey guys i'm making a website where you submit a server for advertising. When the user goes to the index page of my website it grabs the ip's of all the servers submitted and then tests to see if it is online using fsockopen() like so:
while($row = mysql_fetch_assoc($rs)) {
$ip = $row['ip'];
$info = #fsockopen($ip, 25565, $errno, $errstr, 0.5);
if($info) {
$status = "<div><img width='32px' height='32px'
title='$name is online!' src='images/online.png'/></div>";
$online = true;
} else {
$status = "<div><img width='32px' height='32px'
title='$name is offline!' src='images/offline.png'/></div>";
$online = false;
}
}
}
This way works fine, but the only downside is when you load the site it takes a good 2-4 seconds to start loading the website due to the fsockopen() methods being called. I want to know if there is a better way to do this that will reduce the amount of wait time before the website loads.
Any information will be appreciated, thanks.
Store the online status and last check time in a database, if the last check time is longer than 15 minutes for example, update it. I am pretty sure you don't need to get the status on EVERY pageload? It's the time it takes to connect to each server that slows down the website.
Then again, you would probably wanna move the update process to a cronjob instead of relying on someone visiting your website to update the server statuses.
Looking at your example, I'd make all the $status bits be javascript calls to another php page that checks that individual server.
However, the idea to move the status checks to cron job or use some kind of status caching is very good too. Maybe store statuses in a database only only check the ones that have expired (time limit set by you).

How to run a code after a specified time?

I have a big problem:
A user logs in, and the session opens.
After that he clicks a button (in a form) which action is "example.php".
This example.php should increase one record in MySQL database by 1.
How to write this "example.php"?
Please help.
EDIT:
Sorry, I haven't asked what i was supposed to ask.
Main problem:
After a user clicks a button, the example.php script should execute after a specified time, for example, a 600 sec.
The other problem is that the user can click the button and log out, and despite that, the example.php should execute 600 sec later.
EDIT (18:48):
OK, I've read all your suggestions, but dont't have an idea how to make all of this things work together.
I made a form.php, with input type="submit" and action="example.php".
I want to:
1. start a javascript timer;
2. increase a value in database after a time, specified earlier in a variable.
Please, if it is possible, give me an example, how to do this.
In example.php execute SQL:
UPDATE table SET field = field + 1;
Do you need more info to do that ?
EDIT:
I think that there is no other way like jobs mechanism. When user calls example.php, you add to the database new job with a current timestamp + 600 seconds.
Parallel there should be running some job executor that will gather from database all jobs that have timestamp set to timestamp <= NOW().
If it will some records, call specified piece of code and remove/mark as done that jobs.
You may delay the execution of code using sleep
Example:
<?php
echo 'Script Start: '.date('h:i:s') . '<br>';
sleep(5); // delay in seconds (here 5)
echo 'Script Ende: '.date('h:i:s') . '<br>';
?>
I do not know if what you are trying to do makes perfect sense, but your exampl.php would look something like:
<?php
sleep(600); // delay in seconds
// the code to be executed delayed here
?>
There are several ways you could go about doing this...
As mentioned there is the sleep method.
You could have a job - i.e. Add something to a jobs list and have a cronjob check it every so often to see if it is due.
You could use a javascript timer to execute after x number of seconds.
<?php
if( isset($_POST['submit_button']) ) {
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$sql = 'UPDATE table SET counter_column = counter_column + 1'; // WHERE table_name_id =' . intval($id);
mysql_query($sql, $link);
}
?>
This example.php will only update the value if the submit_button is clicked on and not if you just type in the URL example.php

Categories