How to get dynamic home page - php

I have a index.html file consist of certain data with refresh button.
On pressing refresh button it will call refresh.php.
Refresh.php connects database and gets new updated data from database (Say- today's event data) And shows updated data in that refresh.php page
this is what I do.. But I want dynamic home page and want to remove refresh button. In short- whenever user loads homepage..that division should display updated data from database. So should I use .index.php and use php code in index.php itself will work?
I dont want to use asp/ajax/cookie/session. Please give me idea apart from these. Thanks :)

You could check the file's age, e.g.
<?php
$ca_file = '/path/to/foo.blah';
if (is_file($ca_file)) {
// check if file is not older then 1 hour
if (time() - filemtime($ca_file) <1 * 3600) {
$ca_news = 'y';
}
}
That would check if the file is not older then 1 hour. You'll probably want something smaller. Now all you need to do is to check the value of $ca_news and do your magic.

Related

header redirect with include file

I've looked around on here and couldn't locate any solution for my little problem.
I currently have this following IF statment
if($page==1) {
$sql = "UPDATE page SET page='1' WHERE id=1";
INCLUDE 'month.php';
header("Refresh: 10; url=http://XXXXX.co.uk/?p=2");
}
Which currently updates a database according to what page it is on and then includes the current month calendar file and I hoped I could redirect it to page number 2 which is very much similar but loads another calendar and the SQL adds +2 to the database.
In essence it's just a loop I've made and it just reads a SQL database to see what page it needs to load next< I know there's better ways to create a loop (just to scroll through 3 PHP pages) but I'm not that great at PHP..
So i'm just wondering really, could anybody help me to have that include statement along with the header refresh?
Like said the purpose is so that the pages rolls a loop, I've managed to get it all to work with an iframe (instead of the header) but it takes a few seconds longer for the frame window to load.
#Mario that's perfect - I echoed the following:
if($page==1) {
$sql = "UPDATE page SET page='1' WHERE id=1";
echo '<meta http-equiv="refresh" content="5;url= http://XXXXX.co.uk/?p=2"/>';
INCLUDE 'month.php';
}
Which now loads the loop flawlessly - I've been up all night trying to get that working.
Thank you so much
Can I push page transitions I wonder?
Such as 'push out' or 'scroll out' ?

Remember MYSQL query results for use in PHP page

I have a PHP page set up to generate a rather large set of data generated from MYSQL queries.
Using this data it will create a certain number of table headers (in html ) dependant on the number of users currently in the system.
foreach($usersFromMYSQL as $row)
{
echo
"
<th>$someUserData
<th>Col Y
<th>Col Z
";
}
It will then also populate the table with a certain of number of rows (in html ) dependant on the number of events occurring in the system
foreach ($eventsFromMYSQL as $row)
{
echo
"
<tr>
";
foreach($usersfromMYSQL as $inner_row)
{
echo
"
<td>$someUserSpecificEventData1
<td>$someUserSpecificEventData2
<td>$someUserSpecificEventData3
";
}
}
This code is heavily simplified, but identical in format, to my website.
My problem is that I am running my website on a Raspberry PI, and the load times for this page are (expectedly) slow due to the number of users and events in the database. Currently each time you access the page all of this data is requested again, and there is (to my knowledge at least) no form of caching or memorisation involved.
The data can possibly change day by day, meaning that if the page where to be cached, I would want it to only remain cached for the remainder of that day, as the next day could possibly have different results.
My question is what solutions exist to prevent this data being reloaded every time the page is visisted, but ensure that it is at least reloaded once a day?
I assume you use MVC system, then it might be done like this :
In your controller, check whether the view page for that day is exists or not.
If not, then get all query and generate all HTML data and then save it as a view file by using unique file name (ex. 2014_01_01.php). After that, load the page.
If exists, direct load the view page for that day.
Please pay attention that once the page is generated for current date, the script should not generate page again.
EDIT 1
If you are using single file,
<?php
$file_name = date('d_m_Y').".php";
if(file_exists($file_name))
{
//load
$page_data = file_get_contents($file_name);
}
else
{
//generate page here
//
$page_data = "....... YOUR HTML PAGE DATA HERE ........ ";
//save it
file_put_contents(date('d_m_Y').".php");
}
//show page to user
echo $page_data;
?>

Stop rand() code after limited page refreshes

I'm using a code that generate a random word from a database using ORDER BY RAND() LIMIT 1 (not many rows so it runs okay) . Is it possible, using php, to only allow the user to refresh the page a few limited times (either by clicking refresh manually or using a form['submit'] button) and then stopping the random function so it sets to the last value?
I know I can count page visits/refreshes by using sessions/cookies but I'm not sure how to stop the code running.
Barely constitutes an answer but too long for a comment - what is it exactly that you don't get?
<?php session_start();
// ...
if(!isset($_SESSION['myCounter']))
$_SESSION['myCounter'] = 0;
if($_SESSION['myCounter'] < $myLimit){
$_SESSION['myCounter']++;
// Do random DB query
$_SESSION['lastResult'] = $dbResult;
}
// Do something with result
echo $_SESSION['lastResult'];
// ...
There are even examples on the manual pages...
A IF statement would suffice
IF ( pagecount < 3 )
{
Execute code
}
ELSE
{
Don't execute code
}
Set a flag on your PHP Script using a session say, $_SESSION['runRand'] = 1;
Run the random word db code only when the above variable is set to 1.
So when the user runs this script first time...
Store the first random word which was generated from DB into a session variable say $_SESSION['firstRand']=$randNum;
So when the user clicks the refresh button or submit, the PHP script gonna load again and a new random word will be generated, now don't store that word, just compare it to the one with the session variable $_SESSION['firstRand'];
When the user keeps clicking refresh and do the same process again, at some point the random word will match with the $_SESSION['firstRand']; , at that time set the session variable $_SESSION['runRand'] = 0; . Now , eventhough the user presses the refresh button the random code from DB will not be generated.

Update table value on page view?

I am trying to create a PHP trigger for when a user views certain pages on my website it will update the user table in the points section.
I understand the process would work something like this
on page view > update user > where user id is (**get username from session**) > add 5 to points row
Anyone have any idea how to set up something simple like this for giving users simple points for viewing pages?
My site is using PHP and mySQL for the database.
Use cookies or session variables to keep track of the user details like the username or ID. So making a pageview trigger would be as easy as adding a mysql query at the top of every page which would update the database table for views. Kinda the same way that forums operate.
E.g
<?php
session_start();
$db_connection = mysqli_connect('host','username','password','db');
$user_id = $_SESSION['userid']; //That is asssuming that you had gotten the user id on login
mysqli_query($db_connection, 'UPDATE page_views SET views_column=views_column+1 WHERE userid=$user_id');
?>
Yes, you could do something like (if you own the page the user has to visit):
<?php
$pointsForThisSite = 5;
include "points_adder.php";
?>
While Points_adder looks whether $pointsForThisSite is defined and > 0, then adds the Points to the database as you descripbed.
Is that what you are looking for?
Create a php function and call it everytime the user enter the page.
You don't need a mysql trigger because, the action is at the webpage.
function add_points($user, $page){
//If users visits too many maybe you don't want to gave him some points.
//add points
}
and invoke the function in that pages you want to score
The most unobtrusive way to do this is with an AJAX call after the page has loaded. The call should be to an include file that performs the database update operation and returns a 204 response so that the visitor's browser doesn't wait for response content.
For an Apache server;
header('HTTP/1.0 204 No Content');
header('Content-Length: 0', true);
header('Content-Type: text/html', true);
flush();
// do the table update here

Updating multiple page elements without refreshing the page using PHP & jQuery

I have a PHP page that uses jQuery to let a user update a particular item without needing to refresh the page. It is an availability update where they can change their availability for an event to Yes, No, or Maybe. Each time they click on the link the appropriate jQuery function is called to send data to a separate PHP file (update_avail.php) and the appropriate data is returned.
Yes
Then when clicked the params are sent to a PHP file which returns back:
No
Then, if clicked again the PHP will return:
Maybe
It all works fine and I'm loving it.
BUT--
I also have a total count at the bottom of the page that is PHP code to count the total number of users that have selected Yes as their availability by simply using:
<?php count($event1_accepted); ?>
How can I make it so that if a user changes their availability it will also update the count without needing to refresh the page?
My thoughts so far are:
$var = 1;
while ($var > 0) {
count($day1_accepted);
$var = 0;
exit;
}
Then add a line to my 'update_avail.php' (which gets sent data from the jQuery function) to make $var = 1
Any help would be great. I would like to stress that my main strength is PHP, not jQuery, so a PHP solution would be preferred, but if necessary I can tackle some simple jQuery.
Thanks!
In the response from update_avail.php return a JSON object with both your replacement html and your new counter value.
Or to keep it simple, if they click "yes" incriment the counter, if they click No or maybe and their previous action wasn't No or Maybe decrease the counter.
Assuming your users are logged into the system I'd recommend having a status field in the user table, perhaps as an enum with "offline", "available", "busy", "unavailable" or something similar and use the query the number of available users whilst updating the users status.
If you were to do this you'd need to include in extend your methods containing session)start() and session_destroy() to change the availability of the user to available / offline respectively
The best way is the one suggested by Scuzzy with some improvements.
In your php, get the count from the database and return a JSON object like:
{ count: 123, html: 'Yes' }
In your page, in the ajax response you get the values and update the elements:
...
success: function(data) {
$("#linkPlaceholder").html(data.html);
$("#countPlaceholder").html(data.count);
}
...

Categories