I've faced a problem that I can't solve. Thing I want to do, to "save" all output SQL data to file (which should renew at timed interval ex. 5 mins) and print the file out on the website.
This is my example script, which shows data... but it makes connection each time web is loaded.
<?php
mysql_connect($dbserver, $dblogin, $dbpass);
mysql_select_db($dbname);
mysql_query("SET NAMES 'utf8'");
$rektanrekt = mysql_query("SELECT * FROM characters WHERE (accesslevel < '1') order by pkkills desc LIMIT 10");
$i = 1;
echo '<table id="top_table"><tr id="table_title"><td></td><td> </td><td>Nick</td><td></td><td>Kills</td></tr>';
while($row = mysql_fetch_array($rektanrekt))
{
echo '<tr><td id="skaiciai">' . $i . '.</td><td></td><td id="nickas"><font>';
echo $row["char_name"];
echo '</font></td><td> </td><td id="kills"><font>';
echo $row["pkkills"];
echo '</font></td></tr>';
$i++;
}
echo '</table>';
?>
And it does the job done -> http://prntscr.com/a3hpmx
But is it possible to make "backup" of this file, and show it if SQL is offline ... or even better - if SQL is ON update the file each time interval, if SQL is OFF just show latest one?
Saving output data to file:
The simplest way is to output the results in a text file using code similar to the following:
$timeStamp = time();
$pathName = "/gameLog/".$timeStamp.".txt";
$myFile = fopen($pathName, "w");
//+++++++++++++++++++++++++++++++++++
/*here you place your previous code, and inside the while
loop you use the fwrite() function to include the information
you want to save. For example:
fwrite($myFile, ($info."\n"));
where $info is the data you want to include in the file, and
"\n" is the line break.
*/
//+++++++++++++++++++++++++++++++++++
fclose($myFile);
Note: I used $timeStamp = time(); as the name of the file you are saving with the information you wanted because it will consistently generate a new value, hence you won't be overwriting your log files. Also it can help track at what time this log was saved. You could make this cleaner of course.
Doing this in intervals:
As jeroen mentioned, a cron job is probably your best solution to doing so. If you are using CPanel (linux), when you go to the CPanel homepage of your webhosting account (I am assuming your have an account with godaddy or another provider), there should be an option called "Cron Jobs" or something similar. What a Cron Job does is that it is a "Scheduled Event" that is told to execute some file in an interval you specify (you also specify the directory of your file). I found an example on youtube for you, however the video is a bit out of date, though the process should be similar:
https://www.youtube.com/watch?v=bmBjg1nD5yA
Edited: I noticed you are working on L2Aria, if you need any help, let me know! :)
Related
I want to delete data from table at specific time. For example at 15:00.
My code looks like this:
$time = date("H:i");
$timeToDel = date('H:i', strtotime("15:00"));
if($time == $timeToDel) {
mysqli_query($conn,"DELETE FROM table1");
mysqli_query($conn,"DELETE FROM table2");
}
There is that, when i open the page at 15:00, data from database will be deleted, but when I open the page at 15:01, data won't be deleted from database and they will be still visible on page.
Whole script is on hosting and not on my localhost.
Mostly server time is different from local time , So check server time and it's format.
You have to use cron job,Using cron job you can execute file with a specific time. you can learn it from here https://www.siteground.com/tutorials/cpanel/cron-jobs/.
I usually update my site "by hand", entering in one page called "enterheretoupdate.php". This page refreshes every minute to do all the job I need, so while this page is "open", my site keeps refreshing every minute.
What does "enterheretoupdate.php" do? It makes things related to mysql: create tables, selects from tables, add rows to tables, etc. Apart from that, it also make calculations on php and updates .json files.
I would like to create a cron job, so that it is not necessary for me to visit "enterheretoupdate.php" on my computer for updating my site every minute.
I am quite new on this, but I have learned how to create a cron job (I use 1and1). The example cron job I have created, consisting on sending an email every minute, works fine.
But then, I tried to save "enterheretoupdate.php" as a cron job and it does not work. Is there a "limitation" on the things a cron job can do? How should I "translate" my php file to make it work as a cron job?
Any help is really welcome.
This is how my .php file looks like:
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
//Change 1 to reload, 0 to not to reload;
$reload=1;
$gamecode=7;
$cmp="EL";
$year=2017;
if ($reload==1) echo"<head><meta http-equiv='refresh'content=".$sec.";URL='".$page."?gamecode=".$gamecode."&cmp=".$cmp."&year=".$year."'></head>";
include("../newcon.php");
include("../formulas.php");
include_once("funLightCreateTables.php");
include_once("funLightFirstFive.php");
include_once("funLightChanges.php");
include_once("funLightLiveJsons.php");
if ($cmp=="EC") {$l="U";}
if ($cmp=="EL") {$l="E";}
//Check
$q="SELECT * FROM LightLiveSchedule WHERE year=".$year." and cmp=".$cmp." and gamecode=".$gamecode."";
$res=mysqli_query($link,$q);
while ($r=mysqli_fetch_assoc($res)){
$started=$r['started'];
}
if ($started==0){
LightCreateTables($cmp,$year,$gamecode);
$q="UPDATE LightLiveSchedule SET started=1 WHERE year=".$year." and cmp=".$cmp." and gamecode=".$gamecode."";
mysqli_query($link,$q);
}
//Read
$pbp=file_get_contents("http://thesite.com/data.json?gamecode=".$gamecode."&seasoncode=".$l.$year."");
$pbp = json_decode($pbp,true);
//Insert
mysqli_query($link,"Truncate P_Live_Temp_".$cmp."_".$year."_".$gamecode."");
$lres=0;
$vres=0;
$n=0;
for ($i=0;$i<=4;$i++){
$nplays[$i]=count($pbp[$qtitle[$i]]);
$ii=0;
for ($j=0;$j<=$nplays[$i];$j++){
//change results
if ($pbp[$qtitle[$i]][$ii]['PUNTOS_A']!=null) {
$lres=$pbp[$qtitle[$i]][$ii]['PUNTOS_A'];
}
if ($pbp[$qtitle[$i]][$ii]['PUNTOS_B']!=null) {
$vres=$pbp[$qtitle[$i]][$ii]['PUNTOS_B'];
}
//clean
if (strpos($pbp[$qtitle[$i]][$ii]['CSDESCWEB'],"(")==0) {$play=$pbp[$qtitle[$i]][$ii]['CSDESCWEB'];}
if (strpos($pbp[$qtitle[$i]][$ii]['CSDESCWEB'],"(")>0) {$play=substr($pbp[$qtitle[$i]][$ii]['CSDESCWEB'],0,strpos($pbp[$qtitle[$i]][$ii]['CSDESCWEB'],"(")-1);}
//count
$points=0;
if ($play=="Three Pointer") {$points=3;}
if ($play=="Two Pointer" or $play=="Lay Up" or $play=="Dunk") {$points=2;}
if ($play=="Free Throw In") {$points=1;}
//ntconsole=00:00 at End Game
if ($play=="End Game") {$pbp[$qtitle[$i]][$ii]['NTCONSOLA']="00:00";}
//insert
$q="INSERT INTO P_Live_temp_".$cmp."_".$year."_".$gamecode."
(orden,shteam,shloc,shvis,quarter,minute,ntconsole,pcode,play,locres,visres,points)
VALUES
(".$n.",'".$pbp[$qtitle[$i]][$ii]['NTEQUIPO']."','".$pbp['ca']."','".$pbp['cb']."',".($i+1).",
".$pbp[$qtitle[$i]][$ii]['MINUTO'].",'".$pbp[$qtitle[$i]][$ii]['NTCONSOLA']."',
'".str_replace(" ","",substr($pbp[$qtitle[$i]][$ii]['NTJUGD'],1,10))."','".$play."',".$lres.",".$vres.",".$points.")";
mysqli_query($link,$q);
$ii++;
$n++;
}
}
Do you think it is suitable for a cron job? How should I proceed? Thanks a lot!
I had similar issues but the following worked for me.
See the link to change default mysql permission
How to allow remote connection to mysql
Now change your db_server value in the sql connection file from
localhost to 127.0.0.1
In your case the you need to edit the file ../newcon.php it seems.
I am doing this flash banners for multiple clients and one major request is to have some sort of counter so they know how many times the banner has been clicked.
I know how to do it in ActionScript 3.0, I make a simple var:int and i increase it +1 when a click is made on the banner. What do I do with the value of this var(say its 121) where do I store it online so its safe and can be changed by multiple flash banners(as3).
But how do I save this information so next time when the banner is loaded(on diffrent webpages) the number of clicks is whatever it was last time it was loaded.
Should I look into PHP for that ? I have no clue how to do this... some examples, tutorials, whatever works... would be much appreciated.(I am a designer, not programmer...please dont speak php-ish, or you know... :D)
I've googled a bit, and found some help, but i am still confused, and much of it its not AS3, I'm thinking maybe stuff has evolved a bit since the stuff that I found(2008)...
Thank you very much.
You'd have to store (and fetch) the value somewhere - either in the DB, in a text-file, ...
I'd go search for a tutorial on PHP+MySQL. If you don't like PHP-ish, you're probably better of finding another solution though :p
Example tutorial: http://www.freewebmasterhelp.com/tutorials/phpmysql
You need to store the data you want be retrievable/update-able from multiple clients, to be stored on a server.
You can use any server side language with a database.
Server Languages : PHP, ASP.net, JSP, ColdFusion
Database : MySQL, MSSQL, PostgreSQL, Oracle, DB2 etc..
Use whatever combination you are comfortable with.
In general:
You have a web app that increments the counter in the database
call the page using URLLoader from your AS3 banner.
Database
counter_table
-------------
counter INT
PHP File
$db = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database_name');
mysql_query('UPDATE counter_table SET counter = counter + 1');
AS3 Banner
// url request with your php page address
var scriptRequest:URLRequest = new URLRequest("http://www.example.com/script.php");
// loader
var scriptLoader:URLLoader = new URLLoader();
// load page to trigger database update
scriptLoader.load(scriptRequest);
Do you also want to retrieve the value of the number of clicks in Banner ?
Easy solution (really not the best :) You should use one of the other answers.. anyways, make a php file that reads txt file containing the count of visits.. and in your flashbanner just call the php file. It'll add one hit per call..
PHP:
<?php
/**
* Create an empty text file called counterlog.txt and
* upload to the same directory as the page you want to
* count hits for.
*
*
* #Flavius Frantz: YOU DONT NEED THESE:
* Add this line of code on your page:
* <?php include "text_file_hit_counter.php"; ?>
*/
// Open the file for reading
$fp = fopen("counterlog.txt", "r");
// Get the existing count
$count = fread($fp, 1024);
// Close the file
fclose($fp);
// Add 1 to the existing count
$count = $count + 1;
// Display the number of hits
// If you don't want to display it, comment out this line
//echo "<p>Page views:" . $count . "</p>";
// Reopen the file and erase the contents
$fp = fopen("counterlog.txt", "w");
// Write the new count to the file
fwrite($fp, $count);
// Close the file
fclose($fp);
?>
Example code from: (google: php counter file) http://www.totallyphp.co.uk/text-file-hit-counter
Code is not tested, but looks ok. I only commented just a little..
I am writing a script where it checks for an updated version from an external server. I use this code in the config.php file to check for latest version.
$data = get_theme_data('http://externalhost.com/style.css');
$latest_version = $data['Version'];
define('LATEST_VERSION', $latest_version);
This is fine and I can fetch the latest version (get_theme_data is WordPress function) but the problem is that it will be executed on every single load which I do not want. I also do not want to only check when a form is submitted for example. Alternatively I was looking into some sort of method to cache the result or maybe check the version every set amount of hours? Is such thing possible and how?
Here, gonna make it easy for you. Store the time you last checked for the update in a file.
function checkForUpdate() {
$file = file_get_contents('./check.cfg', true);
if ($file === "") {
$fp = fopen('./check.cfg', 'w+');
fwrite($fp, time() + 86400);
fclose($fp);
}
if ((int)$file > time()) {
echo "Do not updatE";
} else {
echo "Update";
$fp = fopen('./check.cfg', 'w+');
fwrite($fp, time() + 86400);
fclose($fp);
}
}
You can obviously make this much more secure/efficient if you want to.
Edit: This function will check for update once every day.
A scheduled task like this should be set up as a separate cron or at job. You can still write everything in PHP, just make a script that runs from the command line and does the updating. Checkout "man crontab" for details, and/or check which scheduling services your server is running.
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