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;
?>
Related
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.
I have been going through pagination tutorials for past 1 week. I have an html page wherein user enter values into the textfields and click submit button. The page then redirects to a php page which displays corresponding output from the sql database. The database makes use of variables which were received by the php script from the HTML page. I am trying to paginate the final table displayed on the php page but have been unable to do so. Relevant Code for the same is:
Search.html
ClOrdID
Symbol
**index.php**
<?php $clordid = $_POST['clordid'];?>
<?php $orderid = $_POST['orderid'];?>
//connected to database using mysqli
$result = mysqli_query($con,"SELECT * FROM abc where clordid like '$clordid' and orderid like '$orderid'
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
echo "<tr>";
for($k=0;$k<150;$k++){
echo "<td>" .$row[$k]. "</td>";}
This code works fine. When I run this query again to calculate total number of rows and also total number of page links to be displayed in pagination, that works as well. However, whenever I click next page using pagination, the code forgets the value of variables imported earlier from html page. I tried to pass it using the url but has been unsuccessful. I believe somehow the values from html page must be retained by the program at all times to make query execute successfully at all times. Can anyone provide me some basic example (or a url) that could help me understand the process? Thanks
You can assign the variable to the session like so:
session_start();
if ($_GET['page_number'] == 1){
$_SESSION['clordid'] = $_POST['clordid'];
}
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.
My website relies completely on a random page generator that loads a page from a text file list. The code was kindly written by "lserni" on the forum. The script has been working perfectly the last few days, and it's happily processed over 100,000 page views in 3 days!
I noticed today however that it seems to have stopped working properly. If you are a brand new visitor to the page, or you've cleared your internet cache/cookies etc - When you load the page for the first time, it doesn't randomly generate a page.. it just shows a BLANK page. If you then refresh the page, the script works perfectly. I just can't get my head round it, but it's now resulted in a large drop in traffic! Hope you can help:
<?php
session_start();
if (!isset($_SESSION['urlist'])) // Do we know the user?
$_SESSION['urlist'] = array(); // No, start with empty list
if (empty($_SESSION['urlist'])) // Is the list empty?
{
$_SESSION['urlist'] = file("linklist.txt"); // Fill it.
$safe = array_pop($_SESSION['urlist']);
shuffle($_SESSION['urlist']); // Shuffle the list
array_push($_SESSION['urlist'], $safe);
}
$url = trim(array_pop($_SESSION['urlist']));
header("Location: $url");
?>
It's actually the LAST item in the file that's used first if there is no session data.
{
$safe = array_pop($_SESSION['urlist']); // gets item at the END of the array
shuffle($_SESSION['urlist']);
array_push($_SESSION['urlist'], $safe); // puts item at the END of the array
}
$url = trim(array_pop($_SESSION['urlist']));// gets item at the END of the array
So if you introduced a newline in your textfile at the end, it may be your issue.
I would suggest, after the header call, add some HTML that explains where the user is being redirected to. All being well nobody will ever see it, but it could help diagnose why the user gets an empty page.
I want PHP to be able to echo the amount of times the page has been viewed. Being a server side scripting language I'm fairly confident there's a way.
This is what I'm thinking...
main.php
<body>
<?php
include("views.php");
$views = $views + 1;
echo $views;
?>
</body>
views.php
<?php $views = 0; ?>
This works, but does not update. (It will display 1, but will not keep counting upon refresh.)
The problem is that the variable $views does not persist from view to view. In fact, the next time someone comes back to your website $views would have been reset to 0. You'll need to take a look at some form of persistence to store the total number of views.
One way that you can accomplish this is to use a database or via a file. If you are using files, you can do the following inside of your views.php file.
views.php
$views = 0;
$visitors_file = "visitors.txt";
// Load up the persisted value from the file and update $views
if (file_exists($visitors_file))
{
$views = (int)file_get_contents($visitors_file)
}
// Increment the views counter since a new visitor has loaded the page
$views++;
// Save the contents of this variable back into the file for next time
file_put_contents($visitors_file, $views);
main.php
include("views.php");
echo $views;
You will need to store the data somewhere. Variables do not keep their state between requests. $views = 0 always means $views = 0, regardless of whether that variable is being included or not.
Write the number of views to a file (file_put_contents, file_get_contents) or to a database to store them permanently.
When you refresh the page, the state is not saved. This $views is set to 0 everytime you begin, and gets incremented by 1.
To increment the count and save the value, you will need to persist the number by either using a database or a file.
Great idea will be to use a database like MySQL. There are a lot of articles over the Internet how to set it up and use with PHP.
What you would probably want to do - update a page row in 'views' every time page is accessed. Simplest way is something like this:
<?php
/* don't forget to connect and select a database first */
$page = 'Home Page'; // Unique for every page
mysql_query("UPDATE views SET num = num + 1 WHERE page = '$page'");