PHP - How many times the page has been viewed - php

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'");

Related

Better understanding on how to pass variables

I have created a website which gets data from two 'different' MySql database tables. The tables have identical layouts (so the numbers in each table differs but 100% similar in ID's and column names). Now I am a complete self-made programming noob so bear with me in the following.
On the websites front page I display some data from both of the two tables. The way I do this is by creating a variable ($tableName) that holds the name of the table I need. This variable is then used for generating the necessary data in another file (data.php) and then displaying that data on the front page by the file design.php. This process is replicated for all tables in the MySql database. (below is a very simplified format).
Frontpage.php:
<?php
include('../connection.php');
?>
<?php
$tableName = table1;
include('../Data.php');
include('../Design.php');
?>
<?php
$tableName = table2;
include('../Data.php');
include('../Design.php');
?>
.....(etc.)
Data.php:
$query = "SELECT * FROM {$tableName} WHERE ID = 1";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
For ($n = 0; $n < 1; $n++){
$dataVariable = $data["columnname"];
}
}
Design.php
<?php echo $dataVariable; ?>
So what happens is that the user goes to the $dataVariable link and is then sent to Ultimate.php which also includes the Data.php file in order to display a hell-uv-alot of data. I therefore have to again declare the $tableName variable in the Ultimate.php file and then duplicate the Ultimate.php file for every single table there is in the MySql database and change href-link in the Design.php file. (very annoying).
My question is: how can I pass on my $tableName variable from the href on the front page to Ultimate.php? I have searched on here and found a way which includes $tableName to the URL opened on Ultimate.php whereafter I use $_GET inside Ultimate.php to collect it. For some reason I couldn't make that work - and i don't know if this is at all a solid way to solve things in my case.
More importantly: I have never worked with programming before so if anyone can advise me whether I am setting this up most efficiently or not that would also be great! I very much welcome links to guides/tutorials which you think might benefit me at this point!
Thanks a lot in advance!
<?php echo $dataVariable; ?>
Then at the top of Ultimate.php:
<?php
$var = $_GET['var'];
?>
This takes the variable off the browser
http://www.example.com/Ultimate.php?var=yourvariable
You can pass variables from a hyperlink to another page using GET.
hyperlink text
$_GET['key']
http://php.net/manual/en/reserved.variables.get.php#refsect1-reserved.variables.get-examples

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.

How can I keep a shopping cart populated when the user navigates away from the 'cart' page, wihtout using a database

I am building a shopping cart with php, and i have all the items able to pass through to the cart page. However, if the user were to navigate away from the page, all the items disappear. I know that I can use to begin a session, but how do i persist data in the session without using a database?
Should I learn HTML5 session-storage?
Thanks, Eric. I agree, 'if it aint broke then dont try to fix it'...so, how exactly do I read/ write data to the $_SESSION array. I have read the php manual page, but still am at a loss...my data doesnt transfer. Here's my code:
<?php session_start();
$mytext = $_SESSION['mytext'];
$mytext1 = $_SESSION['mytext1'];
$mytext2 = $_SESSION['mytext2'];
$mytext3 = $_SESSION['mytext3'];
$price = $_SESSION['price'];
$price1 = $_SESSION['price1'];
$price2 = $_SESSION['price2'];
$price3 = $_SESSION['price3'];
$total = $mytext * $price;
$total1 = $mytext1 * $price1;
$total2 = $mytext2 * $price2;
$total3 = $mytext3 * $price3;
?>'
By default, the PHP $_SESSION variable doesn't use a proper database or need you to install anything in addition to PHP. It will simply store each users session data in a file on your server.
After calling session_start() you can simply read/write data to the $_SESSION array as you would any other array. Look at the session_start() page for an example.
No, I wouldn't do this in HTML 5. PHP sessions have been working well for years and won't have any browser compatibility issues.
EDIT
Are you writing to the array first? If you haven't put the items in, you won't get anything out. You'll notice that on the example in the linked page, there are two pages in play. The first page assigns to the session array. In your code, you only try to take things out of the session array. Until you add items to it, you won't get anything out of it.

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

Categories