[PHP][MySQL] Erased table after 60 seconds of recording - javascript

Im working on kinda program which main part is to count the time which user spent on website, and then to save recorded time in database.
How it works: on the page user has button to start recording his time, then he gets moved to another page, where he can save his time. Saved time is being sent to the php file (through ajax), and then php file puts value in database for current user.
THE PROBLEM is that after 60 seconds of recording time - table in database starts from scratch (00:00:00). For example: if user has already recorded 30 seconds (00:00:30), then he runs the script, records 40 seconds more, and then instead of 00:01:10 in database his score is clear (00:00:00)
Details below.
MySQL Table - type: time
//JS
$("#stopTimer").click(function(event) {
var time = event.timeStamp;
$.ajax({
type: 'POST',
async: true,
url: 'timer.php',
data: {time: time}
});
});
//PHP
$time = ($_POST['time']/1000);
$stmt = $db->prepare("UPDATE members SET timeOnline = timeOnline + '$time' WHERE memberID = :memberID");
$stmt->execute(array(':memberID' => $memberID));

If you want to add seconds to a TIME column use + INTERVAL x SECOND:
UPDATE members
SET timeOnline = timeOnline + INTERVAL :time SECOND
WHERE memberID = :memberID

Try it in another way.
Keep one extra column named start_time . When user first press this button store current time on that.
When user browse in different pages, just calculate the time difference in timeOnline .
It will also be simpler.

Related

Show same content at same time in different browser

I am developing a numbers game where users will buy numbers and after 2 days winners will be drawn.
I am using PHP for the backend and jQuery for the frontend.
My problem is when drawing occurred user on different browser can't see same numbers, these draw numbers are being generated by PHP.
I was thinking maybe I can build these game by PHP and Javascript but it looks not easy. Can you guys please suggest some alternative? How can I improve this code to show the same number on the different browser?
I have the idea that it is not possible to generate a random number for each request. Maybe I can save the number in the database and then get this number in PHP such that the number will be unique for each request.
The actual issue is to create the same content for each user in different browsers. Any help would be really appreciated.
Javascript:
var myTimer = setInterval(checkDrawDate, 1000);
function checkDrawDate() {
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
var x = new Date(dateTime);
var y = new Date("{{$drawDate}}"); //this is laravel variable which contain drawdate e.g. 2017-07-05
if(x >= y){
drawNumber();
}
}
function drawNumber(){
$.get("{{ route('ajaxcomparepowerball') }}",{'gameId': gameid}, function(res){
$('#mybets').html(res.html);
});
}
PHP:
public function ajaxDrawNumber(Request $req){
return rand(0,49);
}
A Cron Job will be needed to implement this functionality. As you are drawing a number on particular time (after $drawDate in your case). So the cron job will execute once in day, check whether $drawDate for each game is today or passed. If condition true, $drawDate <= now, call a function to generate random draw number rand(0,49) and save it to database corresponding to gameid of matched games(having $drawDate <= now).
By doing this, a lot Javascript work will be reduced. In JS, then need to hit an ajax request with gameid to fetch record having draw number for particular game from database. If record not found, it means random number not drawn yet.
I think you are using Laravel, so to schedule tasks in laravel visit here.
Here some possible solutions.
If you need the same data modified for users in real time I think the best option is WebRTC, quick start here. And here a simple example sending strings in real time between clients.
If you also need interaction server to client you could use server-sent events.
You could perform a bidirectional communication between browser and a server using WebSockets. You can send and receive event-driven responses. Using a database you could communicate two clients.
The easiest is using a database to store the information and perform ajax to send data to the server (and database) and server-sent events to send data to the clients.
Basic Server-sent event example:
Javacript:
var evtSource = new EventSource("myserver.php");
evtSource.onmessage = function(e) {
// listening for new messages here
alert(e.data)// e.data is mynumber
}
Php (myserver.php)
<?php
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream\n\n");
while (1) {
//perform a query in your database with your driver
$result = mysql_query("SELECT mynumber FROM mytable WHERE user = 1");
$row = mysql_fetch_assoc($result);
echo $row['mynumber'];//<-- sending mynumber to client
ob_end_flush();
flush();
sleep(1);// <-- this is every second, but you could fire this with ajax or some other event.
}
This code send a number from server to a client that is listening. If a user made a change, one possibility is that client send an ajax to update some value in the database. So, at the same time, the ajax server could send this as an update to clients listening. In that way the whole process is completed.
I think all you need is this. Call a function in every, say 5 seconds or less and fetch data from server and update it in the page.
window.setInterval(function(){
updateNumber();
}, 5000);// set for every five seconds
function updateNumber(){
//ajax code to fetch live data and append the data in the numbers container
}
And dont forget to cross check the data before saving the numbers in the server.
Hope it helps.!!!
To save and maintain users state, key value store like Aerospike can be used. It is very easy to save and retrieve data in key value store. In above case we just have to generate a unique key using gameId, userId and date. And save user's data against the unique key.
To get started with Aerospike php client following is Aerospike php client
If data is present against the unique id for that particular user just return it, else create the new random number save it against the unique key and return it. Please be careful while creating unique key. Instead of using server side date-time please send date in ajax call request so there will not be any issue with time zone. It will be always user's timezone and there will not be any issue if server is in different timezone and user is in different timezone.
function drawNumber(){
$.get("{{ route('ajaxcomparepowerball') }}",{'gameId': gameid,'date':user-timezone-date}, function(res){
$('#mybets').html(res.html);
});
}
Here "user-timezone-date" should be fix date format like 'MM-dd-yy' which will indicate the same day. hours or seconds should not be included while generating unique key otherwise at the time of retrieving the user's state; generating particular unique will be changed every hour or every second and whole purpose of of doing this will be shattered.
I am new to StackOverFlow so I am not able to comment on the answers. In case of corn job as well we have to be careful with time-zones if server and users are in different time zones. Otherwise user's will see different random number before user's day is complete. Please improve answer by commenting on it and suggestions are always welcome.

Store time in local storage

I'm trying to push a lapsed time to local storage. Whenever the user clicks a submit button a clock stops and a duration is calculated. I want to push that duration time to an array in local storage. And after the last click I want to fetch the entire array to calculate the total time. There are several similar questions in SO but none of them siuts this purpose fully. I can see in my local storage that an array with key: 'Time' has been created but it isn't populating.
Code:
let answerButton = document.querySelector('#send')
answerButton.addEventListener('click', function () {
TotalTime.stop()
TotalTime.duration()
clearTimeout(window.countdownTimer)
timer()
let totalTime = []
TotalTime.duration().push(window.localStorage.setItem('Time', JSON.stringify(totalTime)))
})

Setting up a delay notification with php

I need to write a php function for sending a Telegram notification after 4 hours.
With the application i'm posting data into a SQL db, after I pressed the Submit button, i need that a php function starts and after 2 days sends to my Telegram channel a notification, with some of the data that i've posted into the db record.
For the posting part and Telegram part i'm ok, i've already linked the website to the channel and normal notifications from php work fine, but i need some advice on the "reminder" part.
I was thinking about some date() function and post the value in to the record, make another var with the date + 2days e make some for or while cycle but i don't think that this can works. Some advice?
I'm new to php, maybe i dont know some function that could help me?
Add to your table a column and name it notification_send and give it a default value of 0
Create a crontab that calls a php file for example:
*/60 * * * * php -f /etc/www/my_notification.php : calls the file every 60 mintues
In this file create a query that selects all the data with the notification_send = 0 then check if the current_date - date column of each row => 2 days :
If so : update the notification_send value to 1 and send your notification
As I commented, your approach is right. As you asked something more, though, I chose to write an answer.
As you asked, when you send a Telegram notification you have to send a reminder notification after 2 days (48h). If I'm right it's an e-mail.
First of all, as you said, you have to create a column to warn when the remember should be send.
Also, to know if the reminder has been sent or not you have to create another column. It could be a flag (true/false) or a datetime column (null = not sent, filled = sent).
Besides that, a cronjob or schedule have to call a PHP script. I'll show to you an example of a PHP script.
I'll call the table as reminder and the column sendIn and isSent.
//select only the reminder that has the sendIn lesser than now and that not has been sent
$statement = $pdo->query("SELECT * FROM reminder WHERE sendIn <= NOW() AND isSent is null");
//prepared statement to update the reminder sent
$updateStatement = $pdo->query("UPDATE reminder SET isSent = NOW() WHERE id = :id");
foreach($statement as $reminder)
{
/**
script to send the reminder
**/
//update the reminder
$updateStatement->execute(array(':id' , $reminder['id']));
}
To create a cronjob, you could take a look here:
https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job
You don't need to delete the cron, just let it run periodically and send all your reminders.

variable value on page change

I am new in javascript and php. I am creatng an admin panel in which I have an option for the user to play game. But the issue is, every game have a specific time period say 30 mins. So, what I want is that if a user have started the game, the count down must be started and if user once switch from that page to another page, still the counter must be counting and after 30 mins it should end the game.
For example I am on http://www.examplec.com/Game1 my count down of 30 min will start. If I switch from that page to another like http://www.example.com/order then the counter should still count the total time and when its expired, end it and send query to database.
Kindly reply if anyone know the solution. I have already find a solution using session but I want more efficient solution. One more thing a single user can play more than 1 game.
when your game start set a session of current time like this
$_SESSION['game_start_time'] = strtotime(date('d-M-Y g:i:s A')); // it will give you complete current timestamp.
and now check it on every page by including
if(isset($_SESSION['game_start_time']))
{
$game_start_time = $_SESSION['game_start_time'];
$current_time = strtotime(date('d-M-Y g:i:s A'));
$time_diff = $current_time - $game_start_time;
if($time_diff>(30*60))
{
//expire 30 minutes your code is here
}
else
{
// action if require to do when below 30 minutes of game start.
}
}
What you could do is create a table to keep track of the time, this is not the most efficient way but it would be secure.
So create a new table called gametrack with the following fiels:
id
userid
gameid
timestarted
etc
so when a user starts a game you insert a record with user info.
Next you need to edit the game page. In the game page you could place a jquery code to request for update on the time.
function gameStatus(){
$.ajax({
url: 'status.php?gid=[GAMEID]',
success: function(data) {
if(data == 1) {
//DO SOMETHING, REFRESH THE PAGE, STOP THE GAME ETC
}
}
});
}
setInterval("gameStatus()",10000);
the code above would request status.php every 10 seconds, you need to pass the gameid to the file and assuming that the user is registered you can use session to get user info and return 1 if 30 mins has passed.
You can mix this solution with Satish's Answer to use Sessions instead of Databases and still get a live count down with the jquery code above.
You can try this with localStorage
When you want to set variable:
var name = "value";
localStorage.setItem("someVarName", name);
And in any page (like when the page has loaded), get it like:
var Name = localStorage.getItem("someVarName");
Browser compatibility caniuse.com/namevalue-storage
Demo

check if JSON data has changed and alert rows

I am trying to develope a app that checks MYSQL table every minute for new messages and if there is any it should alert the user and show the message. This is the code I use, how should I modify it to make it work?
setInterval ( "getMessages()", 60000 );
var oldmessage = "";
function getMessages() {
$.getJSON(serviceURL + 'messages.php?ID=' + ID, function(message) {
if(JSON.stringify(message) != JSON.stringify(oldmessage)){ // old message is not same as new
var messages = data.key[0];
alert(messages.NEW);
});
oldmessage = message;
}
So what I'm trying to do is save old message to variable and compare it after minute, and if it has changed I alert row NEW
The possible solution is, you take a new column in mysql to mark as viewed or not. By default that will be not viewed (say 0). In your PHP code you should retrieve one row which is marked as "Not viewed" or 0. And same you should display via AJAX and update back that row with 1 (viewed).
If you dont receive any rows, send nothing to AJAX and handle the messages accordingly no new rows found.
This is just a logic and hope it helps.

Categories

Resources