ajax sum total number of VIEWS - php

I have a statistic on my page which shows the TOTAL NUMBER OF ARTICLE VIEWS...
here is the code I wrote to have the total number of views:
$db = JFactory::getDBO();
$total_views = "SELECT SUM(times_viewed) FROM #__hdflv_upload";
$db->setQuery($total_views);
$result = $db->loadResult();
What I'm trying to achieve is, UPDATE this total number of Views AJAX on page, so if I get for example +10 views in the last 5 seconds, the total number of views must SUM +10 AJAX... without page reload....
I searched in google etc.. but didn't find nothing close to this that can help me... can somebody PLEASE give me a hand. THANK YOU VERY MUCH.

On your statistic page, you could set a JS timer which uses .ajax to get the SQL results every 5 seconds. The script it calls can return the query result in JSON format, then update your DOM accordingly.
There's a pretty good answer at Joomla Stackexchange which should help you get a Joomla AJAX call working properly to run the SQL and return the result.

Related

Dynamic PHP / MYSQLi Pagination

I'm trying to make pagination work on my site dynamically and I'm not sure how to change regular pagination to accomplish what I need to do and I was wondering if a PHP guru could help out!
Basically, once a week a report runs and populates records for the last week in my database. Also, at the end of the month, the report runs and pulls in the last month of data.
I would like to build my PHP page so that all items in the same month (~4-5 weeklies and 1 monthly) show up on the same page, and that each pagination page is a different month's data.
Currently the weeks are stored as two fields, start and end date, in the format: 2018-mm-dd.
How could I have it so that page 1 is all 2018-03 records, page 2 is all 2018-02 records and page 3 is all 2018-01 records? I also would like this to be automated so each newest month becomes thE new page 1.
Does this make sense? Is this possible? Any assistance would be greatly appreciated!! Thank you very much!!!

Mysql_query how to use it with a "dynamic" database?

Today i'm working on my website, trying to display the last winner of the game. Here's my code :
$lastgame = fetchinfo("value","info","name","current_game");
$winnercost = fetchinfo("cost","games","id",$lastgame-1);
$winnerpercent = round(fetchinfo("percent","games","id",$lastgame-1),1);
$winneravatar = fetchinfo("avatar","users","steamid",$lastwinner);
$winnername = fetchinfo("name","users","steamid",$lastwinner);
echo '<p>Game #'.$lastgame.'</p>';
echo '<p>'.$winnername.' won the jackpot</p>';
echo '<p> valued at '.$winnercost.'</p>';
echo '<p>with a winning chance of '.$winnerpercent.'</p>';
The point is i use fetchinfo only, so it displays informations but not in real time, i have to refresh my page to display the latest winner. I'll need to make a mysql_query i guess.
My problem is that i don't understand how to use the mysql_query, knowing that each time a winner wins it creates a new row in my table. For example :
id : 1
startime :1441330544
total price : 3.17
Winner : Foxy
steam id : 76561198042016725
Percent chances to win : 98.7381703
Number of total item : 2
module : 0.24973750
Anyone has a solution to help me ? this -1
,$lastgame-1),1);
gives me some difficulties :(
The result on the website atm :
Game #4
Foxy won the jackpot
valued at 3.31
with a winning chance of 94.6
Based on the information you provided, I think the simplest query you could use would be something like:
select * from <tblname> order by steamid desc limit 1;
For the auto refresh you could do one of two things:
1) you could add: <meta http-equiv="refresh" content="5"> in the header of your html and the page will automatically refresh every 5 seconds. (basic)
2) you could use ajax to make a call to execute the query and update the page which is a much nicer user experience (more advanced)
Make an api page with a php or any other preferred serverside programming web language that when called gives you the most up to date query results it can.
Then create a loop in javascript that every x amount of seconds sends an ajax request to the api page and using that data,you can dynamically update your fields with jquery or js (really doesnt matter - you probably know how to update/change text)
Here some resources:
ajax getting started
link 1
more ajax
link 2

"Loading Record Number [##] of [Total]" progress bar

I have a problem that may not have a solution, but hopefully someone out there can figure this out.
I developed a website in PHP/MySQL that uses HTML/CSS to process payroll. When the user submits the payroll for the past (2 week) period, it processes each employee's hours. For companies with <50 employees, it can process it pretty fast, but for companies with over 100 employees, it can take quite a while to process. What I would like ideally is not a generic 'Loading' bar or an estimated '35% loaded' bar since each company's payroll will vary greatly in employee numbers.
The best solution would be that as soon as they submit the pay period, I could pass the total record number from the PHP/MySQL processor/DB, then update the number as each employee is processed from the PHP processor, so the user would see "Processing Employee 35 of 134" for example where '35' would increment and be updated as each record is processed. Or, if not possible, I'd even be fine with a dynamic list such as:
Processing Employee 1 of 134
Processing Employee 2 of 134
Processing Employee 3 of 134
Processing Employee 4 of 134
and so on ...
Ajax or Javascript seem to be the best options to achieve this, however I can't figure out yet how to use them to achieve this. Any help or insight would be greatly appreciated. I'll continue looking and update this post if I find anything as well.
I've done that by calling the flush() command in PHP while iterating through the batch, but you could get tricky and update a hidden field and have a javascript function on setTimeOut check that value and update a progress bar.
http://php.net/manual/en/function.flush.php
And progress bar:
http://docs.jquery.com/UI/Progressbar
What I would do with the dynamic list is:
$count = 0;
// some db query
// start output
echo "<ul>";
// iterate through records and perform dynamic insert
$count ++;
echo "<li>Processed " . $count . " records.</li>";
flush();
// end iteration
// end output
echo "</ul>";
If you want to only update every % of records, then like you stated get a total count, then perhaps use a modulus operator in if clause. For example if you had 50 records and you wanted to update every 5, if($count mod 5 == 0) { echo ... flush() }
You would have to make a combination of what Mike S. suggested and quick ajax calls (say every 500 ms) You could make an ajax call to a text file that is written to from your PHP file....
For example:
<?php
$count = 0;
mysql_connect('blahblah');
// start output
$query = mysql_query("SELECT ...");
while($rs = mysql_fetch_assoc($query)) {
$fh = fopen('filename.txt','w');
fwrite($fh, $count);
fclose($fh);
++$count
}
?>
Then you need to make an ajax call every 500 ms (or sooner than that) to that filename.txt file and read the contents of that file to see how far along you are in processing your request. You could even do something similar to write in the contents of the php file [current_count]-[total_count] (15-155 for on record 15 of 155 total records) and do results.split('-') in your javascript coding.
My approach would be to store the total number of records and the current record number in session variables. Then set up a php page that returns the text/html of "Processing employee $currentRec of $totalRec".
When you submit the request from the main page, display a div on the page to show the status message. Fire off an ajax request to process the data and have it hide the div when it is complete. The code that processes the records can update the session variable as it goes along. At the same time fire off a periodical ajax request that gets the status message and updates the div's contents with the response. Have this continue until the div is no longer visible. You should have a status message on the page that pops up while the data is being processed to display the current record number, and it will update as often as you like based on how you set up the update timer.
The exact implementation would depend on whether you are using jQuery, prototype, plain Javascript, etc...

Storing and Displaying Live Stats

Say we are a site receiving massive amounts of traffic, Amazon.com size traffic. And say we wanted to display a counter on the home page displaying the total number of sales since December the first and the counter was to refresh via ajax every 10 seconds.
How would we go about doing this?
Would we have a summary database table displaying the total sales and each checkout would +1 to the counter and we would get that number every 10 seconds? Would we COUNT() the entire 'sales' table every 10 seconds?? Is there an external API I can push the stats off to and then do an ajax pull from them?
Hope you can help, Thanks
If your site is ecomm based, in that you are conducting sales, then you MUST have a sales tracking table somewhere. You could simply make the database count part of the page render when a user visits or refreshes your site.
IMO, there is no need to ajax this count as most visitors won't really care.
Also, I would recommend this query be run against a readonly (slave) database if your traffic is truly at amazon levels.
I would put triggers on the tables to manage the counter tables. When inserting a new sale the sum table would get the new value added to the row for the current day. That also gives sales per day historically without actually querying the big table.
Also, it allows for orders to be entered manually for other dates than today and that day get updated statistics.
As for the Ajax part that's just going to be a query into that sum table.
Whatever you do, do not re-COUNT everything every 10 seconds. Why not to have a cronjob, which does the counting of data every 10 seconds? It could take current time-10 seconds and in slave database add the difference to current count ?
Still 10 seconds sound bizarre. Every minute, mm?

How to perform page control?

I mean what the most efficient way to get information about the quantity of your page's items and make sql query with LIMIT that you need. or I should get all items and then crop array with php functions?
now I do 2 queries: first to count all items and second to get items that I need with LIMIT.
OK, I'll be more concrete. For example I need to show a question on my page and 20 answers to this question. At the bottom there shold be page control: links to the next, prev page and so on. I want to show proper number of links (number of answers/20) and when I go to any link I want to recieve proper answers (for example 41 to 60 on the 3d page). So what's the best way to get number of items (answers) to show proper number of links and to get proper answers for each link?
I guess your'e trying to say you want to know how many items/answers there is in the query but only read up to 20 items at at time, for pagination.
Firstly: You really should look for a pagination package; lots and lots of people have had the same problem before and there probably exists both free/opensource and proprietary solutions for your programming language and framework. (If you say what language you are using I'm sure someone can reccomend a solution for you.)
Anyway, I know I like to know how things work, so this is how it usually does:
As far as I know the pagination code calculates the pages by doing one query using select count(*) from tblX where something divide this number with the items-per-page number and use ceiling (e.g. 4.1 => 5).
For listing the results per page a new query is required; don't worry the count query is terribly much faster than getting every result discarding the ones you don't need DO NOT DO THAT (that's the recipie for becoming the top story on this page). Something like select * from tblX where something limit Y offset Z where Y is the number of items per page, and Z is the the (requested_page - 1)*Y; page 1 will have offset 0, page 2 have offset 20 (if thats what Y are) etc..
But do not try to implement this manually, it's unneccesary, tedious and error prone, much better to use your time customizing a readymade solution.
I'm assuming you want a count of the number of rows you'll be reading so as to do some pagination or similar? I don't understand your need for the LIMIT in the context of your question. However, if you just want a count of how many rows have been found, use one of the following.
You select the count of all rows such as:
select count(*) as counted, name, address
from contact
Or found rows:
SELECT SQL_CALC_FOUND_ROWS, name, address
from contact
This may be mysql specific I'm not sure.
Update:
For pagination you would do something like the following - (Psuedocode)
$rows = array($result)
$num_rows = sql_calc_found_rows
$per_page = 20
$pages = ceil($num_rows / $per_page)
page
$rows_this_page = array()
$rows_this_page = get_values($rows, (min index)$page_number * $per_page - $per_page, (max index)$page_number * $per_page - 1)

Categories