Write in MySQL database when something happens? - php

I'm building a game with javascript where you can walk and pick up things, right now it works fine but it doesn't save the things you have picked up on my database so when you quit the game you lose your progress.
I need to save to my database every time the user walks into something (when a div has a certain position). Right now there is a big javascript IF that basically deletes the item from the map.
Is it possible to make the javascript run the PHP code that writes in the database? How could I do it?

Since Javascript is client-side code, you can't simply call PHP (server-side code) with it. What you can do is post to a page that runs PHP code, using AJAX for instance.

The way you would do it is simple.
Every time the player does an action, have your script make an ajax call to the server to save the location (or what ever you are saving). You can just add a function to the part of your code, so when it is called, it sends the request in the background and saves the value to your databse. The only thing if that you would have to split the ajax requests up, so you only do one every 5-10 seconds. If you dont do this, then you would basically DDoSing you server.

you need ajax
http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html

Related

PHP Reloading data on interval, not refresh

i have a php script that scrapes data from a bunch of websites and stores them in a db. What i want to happen is instead of having the php load at every connection, i want to set it on a 10 minute interval that then stores the data it gets into a DB so i can instantly retrieve info instead of having to have the php run everytime which takes up time. I don't know ajax well and would like to keep it as php/mysql as possible. Any help is apreciated.
TL;DR: Want php to save data to a db every 10 minutes then output that db the same way until it gets over written, instead of loading new data on a refresh.
Basic options as follows. No need (or use) for AJAX here.
Make a cron job / scheduled task (Linux / Windows) that calls your script at intervals.
Add a timed javascript browser refresh to your PHP script. See here for how.
Use a browser plugin like "Easy Auto Refresh" (Chrome) or "ReloadEvery" (Firefox).
The first one is the cleanest way around, spares you from keeping a browser tab open.

Executing PHP code after a specific time

Let's say that there are two PHP functions.
function first()
{
$keyword = $this->input->post('keyword');
//search for the result and show it to users.
$this->search->search($keyword);
//send the keyword to save it into the db.
$this->second($keyword);
}
function second($keyword)
{
//saving a search keyword in the db
}
I would like to send the result as soon as possible and save the search word into DB.
However, I want to run the second script later after specific time.
because I want to deliver the search result as soon as possible to my customer.
Is there a way to run second PHP script after a user run the first PHP script?
* I don't want to use Cron Job
* I wanna run those two script separatly.
* don't want to use sleep because it will stop the first script for certain times.
You'll need to route it back round to your server, but this asynchronous php approach works quite nicely (I've been using it for about a year to do almost exactly what you seem to be doing).
See: How to run the PHP code asynchronous
Instead of making a web request from PHP, as suggested by Bob Davies, I would initiate a new HTTP request from the html page after the page has been shown.
For example:
Client makes an HTTP request (search)
Server gets the stuff and returns results to the end user
The result HTML contains a snippet, such as < img src="empty.gif?searchterm=mysearch"/> which initiates another request when browser renders the html
When that another request hits your server, you can save the search to DB
Similar methods are used to do for example client tracking, when you don't want the end user having to wait your metrics stuff. Some points:
It is quite simple to understand, implement and debug, which (to my opinion) doing HTTP requests on the server side aren't
It's more scalable
It doesn't require having javascript on, just a browser rendering the HTML
The target can be any server anywhere which doesn't have to be accessible from your web server, just to end user.
If you want to use PHP only then as far as I know, you can use sleep(), but it delays the execution of the code.
I think the easiest way to delay the job is with AJAX. Simply put the second function inside another PHP document and call XMLHTTPRequest() or $.ajax (if you want to use jQuery), and delay the code for some seconds. You can do that with setInterval(), or with delay() (jQuery).
Simply write
delay(2000).function(){
//saving a search keyword in the db
}
Remember that here you should use AJAX and not PHP code.

Refresh a page after data in MySQL database changes

Good day all,
Basically what's I've got is a PHP based site tied to a MySQL database all on a local web server (nothing is being accessed from outside of the company). The index page displays an image resembling a bar chart. Employees of the company will be entering data periodically which will update the image that appears on the index page. The index page will be displayed on a couple different screens throughout the company and I need that index page to refresh after someone alters the data in the database.
I've been messing around with various AJAX solutions, but as I don't know much about AJAX I'm having trouble adapting something to work the way I need. Here's the way I've was thinking about:
-- on the index.php run a JavaScript function every minute or so that gets a response from dataChanged.php
-- dataChanged.php will query the database and get a timestamp from one of the tables.
-- the script on the index.php will then compare the timestamp to the last time the page was refreshed (or some variable that stores such information) and refresh if the data is new.
I'm somewhat proficient in PHP, but am very limited with JavaScript (and thus AJAX).
Can someone get me pointed in the right direction?
Thanks!
What you want it the standard javascript function setInterval
Have it execute a ajax call every now and then to get new data. Try to get a standars librabry that knows this stuff, probably jQuery
Depending on if the chart generation is time consuming or not I would go with different strategies. The preferred way would be to just generate the graph on each call, but if that is very time consuming I think your two-step solution works great.
Check out the link http://blog.codebusters.pl/en/auto-refresh-content-after-changes-in-database-ajax.
Here you can see how to refresh your page after change in db.

Is there a way to grab files from other servers and dump them into the DB asynchronous?

I need to create a php script that takes lots of URL's via POST and then loads the corresponding files and dumps them in the DB. The thing is that I would like to do it asynchronous, so that if I have 1000 files to get, the script won't hang till all the files are loaded. Also, every time a file it's done loading, I need to know so that I can insert it in the DB
Any ideas are appreciated.
Split the script in two parts - first to collect the URLs and the second is a shell script to be run from background to get the urls inserted in the database and fetch them.
So basically the process is as follows:
Script1:
Gets POST
Inserts into database
Call script 2 with
shell_exec to run in background
Script2:
Get all the urls from urls_to_download
Fetch the URLS (consequentially or parallel, depends on you)
Do stuff with them
Save them to database.
And you are done. The POST in script1 returns immediately and the script2 is then running. All left for you is to check status (poll from database through AJAX may be) for the URLS if you want to show some information about progress.
PHP is not multithreaded and perfectly synchronous. So you may not do this using PHP alone.
But you may use another language to do this task, for example JavaScript (which is asynchronous). Try node.js. It is lightning fast and has mysql bindings ;) Use http.Client to make the requests to the sites.

PHP display progress messages on the fly

I am working in a tool in PHP that processes a lot of data and takes a while to finish. I would like to keep the user updated with what is going on and the current task processed.
What is in your opinion the best way to do it? I've got some ideas but can't decide for the most effective one:
The old way: execute a small part of the script and display a page to the user with a Meta Redirect or a JavaScript timer to send a request to continue the script (like /script.php?step=2).
Sending AJAX requests constantly to read a server file that PHP keeps updating through fwrite().
Same as above but PHP updates a field in the database instead of saving a file.
Does any of those sound good? Any ideas?
Thanks!
Rather than writing to a static file you fetch with AJAX or to an extra database field, why not have another PHP script that simply returns a completion percentage for the specified task. Your page can then update the progress via a very lightweight AJAX request to said PHP script.
As for implementing this "progress" script, I could offer more advice if I had more insight as to what you mean by "processes a lot of data". If you are writing to a file, your "progress" script could simply check the file size and return the percentage complete. For more complex tasks, you might assign benchmarks to particular processes and return an estimated percentage complete based on which process has completed last or is currently running.
UPDATE
This is one suggested method to "check the progress" of an active script which is simply waiting for a response from a request. I have a data mining application that I use a similar method for.
In your script that makes the request you're waiting for (the script you want to check the progress of), you can store (either in a file or a database, I use a database as I have hundreds of processes running at any time which all need to track their progress, and I have another script that allows me to monitor progress of these processes) a progress variable for the process. When the process begins, set this to 1. You can easily select an arbitrary number of 'checkpoints' the script will pass and calculate the percentage given the current checkpoint. For a large request, however, you might be more interested in knowing the approximate percent the request has completed. One possible solution would be to know the size of the returned content and set your status variable according to the percentage received at any moment. I.e. if you receive the request data in a loop, each iteration you could update the status. Or if you are downloading to a flat file you could poll the size of the file. This could be done less accurately with time (rather than file size) if you know the approximate time the request should take to complete and simply compare against the script's current execution time. Obviously neither of these are perfect solutions, but I hope they'll give you some insight into your options.
I suggest using the AJAX method, but not using a file or a database. You could probably use session values or something like that, that way you don't have to create a connection or open a file to do anything.
In the past, I've just written messages out to the page and used flush() to flush the output buffer. Very simple, but it may not work correctly on every web server or with every web browser (as they may do their own internal buffering).
Personally, I like your second option the best. Should be reliable and fairly simple to implement.
I like option 2 - using AJAX to read a status file that PHP writes to periodically. This opens up a lot of different presentation options. If you write a JSON object to the file, you can easily parse it and display things like a progress bar, status messages, etc...
A 'dirty' but quick-and-easy approach is to just echo out the status as the script runs along. So long as you don't have output buffering on, the browser will render the HTML as it receives it from the server (I know WordPress uses this technique for it's auto-upgrade).
But yes, a 'better' approach would be AJAX, though I wouldn't say there's anything wrong with 'breaking it up' use redirects.
Why not incorporate 1 & 2, where AJAX sends a request to script.php?step=1, checks response, writes to the browser, then goes back for more at script.php?step=2 and so on?
if you can do away with IE then use server sent events. its the ideal solution.

Categories