PHP videos multiple pages doesn't work correctly - php

I'm working on a simple vlog site project and I'm trying to show only 20 video thumbnail per page and I've wrote this code in the index to divide the videos to multiple pages and then pagination them ... the problem is that it shows the same first video's thumbnail 20 times per page for infinity pages.
I really need help with this code
<?php
require_once ('db.php') ;
require_once ('VideosApi.php') ;
$count = mysql_query('SELECT COUNT(id) AS numb FROM videos ORDER BY id');
$array = mysql_fetch_assoc($count);
$number = $array['numb'];
mysql_free_result($count);
$PerPage = 20;
$nbPage = ceil(abs($number/$PerPage));
if(isset($_GET['page']) && $_GET['page'] > 0 && $_GET['page'] <= $nbPage && preg_match('#^[0-9]+$#',$_GET['page'])){ $cPage = $_GET['page']; }
else{ $cPage = 1; }
$Query = mysql_query('SELECT * FROM Videos ORDER BY id LIMIT '.(($cPage-1) * $PerPage).','.$PerPage);
$videos = Videos_Get() ;
if ($videos == Null)
die ('problem');
$vcount = #count ($videos) ;
if ($vcount == 0)
die('no videos') ;
For ($i = 0; $i < $vcount; $i++)
{
$video = $videos [$i];
if ($video->time > 3600)
$duration = gmdate("H:i:s",$video->time);
else
$duration = gmdate("i:s",$video->time);
while($Rows = mysql_fetch_assoc($Query)){
echo ( "<div class=\"video\">
<img src=\"$video->img\"><span class=\"class-video-name\">$video->name</span>
<div class=\"class-video-footer\">
<span class=\"class-video-duration\">$duration</span>
</div>
</div>") ; }
} ?>

A few tips before we get to the answer proper:
Don't use mysql_*. That family of functions is now deprecated and support will be dropped in future versions of PHP. For code longevity, consider using MySQLi or PDO.
Use is_numeric() to check if a string has a numeric value. Using preg_match() is very load heavy for such a simple task.
Try to avoid using SELECT * inside of MySQL queries. Very rarely do you need everything from the table so fetching all fields for rows is very inefficient (especially if you're not using indexes optimally).
That having been said, I've taken some time to rewrite your code following the practices I've preached above. Below is the modified code, and underneath that an explanation of what was wrong:
Update db.php as follows:
<?php
$db = new PDO( 'mysql:dbname=DATABASE_NAME;host=127.0.0.1', 'DATABASE_USER', 'DATABASE_PASSWORD' );
?>
Now for your main file:
<?php
require_once 'db.php';
require_once 'VideosApi.php';
$count = $db->query( 'SELECT COUNT(id) AS total FROM videos' )->fetchObject();
$number = $count->total;
$perPage = 20;
$pages = ceil( $number / $perPage );
$page = ( isset($_GET['page']) ) ? $_GET['page'] : 1;
$page = ( $page < 1 || $page > $pages || !is_numeric($page) ) ? 1 : $page;
$offset = ($page - 1) * $perPage;
$query = $db->query( 'SELECT id, img, name, time FROM videos ORDER BY id LIMIT '.$offset.','.$perPage );
if( $query->rowCount() < 1 )
{
die( 'No videos' );
}
$html = '';
while( $video = $query->fetchObject() )
{
$duration = ($video->time > 3600) ? gmdate('H:i:s', $video->time) : gmdate('i:s', $video->time);
$html.= '<div class="video">';
$html.= "\n\t".'<a href=\"video.php?id='.$video->id.'">';
$html.= "\n\t\t".'<img src="'.$video->img.'" />';
$html.= "\n\t".'</a>';
$html.= "\n\t".'<span class="class-video-name">'.$video->name.'</span>';
$html.= "\n\t".'<div class="class-video-footer">';
$html.= "\n\t\t".'<span class="class-video-duration">'.$duration.'</span>';
$html.= "\n\t".'</div>';
$html.= "\n".'</div>';
}
echo $html;
?>
The problem with your original code is a little hard to determine since you do not provide the contents of VideosApi.php, which is where I assume you define Videos_Get(). Anyway, what I suspect is happening, is that Videos_Get() is actually ignoring all of your pagination, but as I say, it's difficult to diagnose because we can't see all of your code!

Related

set pagination pagenumber as default url

So i managed to build a working pagination system in php. But i want users to default to the first pagenumber of said pagination, so for example if somebody clicks on category 1 the URL will change to this website.php?category=1 i would like this to be website.php?category=1&pagenumber=1 as the default URL.
The reason why i want this is so i don't have to write 2 different query's: 1 if the category isset but no pagenumber, and 1 if both are set.
function getNews()
{
// check if category is get via URL
if (isset($_GET["category"]) && is_numeric($_GET["category"]) && intval($_GET["category"])) {
// bind get category to categoryId
$categoryId = intval($_GET["category"]);
// if category is 1
if ($categoryId == 1) {
try {
$db = new Connection();
$database = $db->openConnection();
if (isset($_GET["pagenumber"]) && is_numeric($_GET["pagenumber"]) && intval($_GET["pagenumber"])) {
$pageNumber = intval($_GET["pagenumber"]);
$itemsPerPage = 9;
$offset = ($pageNumber - 1) * $itemsPerPage;
$stm = $database->query("SELECT * FROM blog where blog.Categoryid = $categoryId LIMIT 9 OFFSET $offset ");
$stm->execute();
$rowNews = $stm->fetchAll(PDO::FETCH_ASSOC);
$totalItems = $database->query("SELECT COUNT(*) FROM blog where blog.Categoryid = $categoryId")->fetchColumn();
$totalPages = intval(ceil($totalItems / $itemsPerPage));
$previousButton = ($pageNumber + 1) - $totalPages;
$nextButton = ($pageNumber) * $totalPages;
$pageIndex = 0;
this is what i currently have(i cut out the pagination system, can paste it in if needed).
//
this is how i generate my category select
<?php
if (isset($_GET["category"])){
$db = new Connection();
$categoryId = $_GET["category"];
$database = $db->openConnection();
$stm = $database->query("SELECT * FROM category");
$stm->execute();
$fetchCategory = $stm->fetchAll(PDO::FETCH_ASSOC);
foreach ($fetchCategory as $cats) {
?>
<a class="dropdown-item" href="blog.php?category=<?php echo $cats["categoryid"]; ?>"><?php echo $cats["categorytitle"]; ?></a>
<?php
}
?>
<?php
}else{
$categoryId = 1;
}
?>
</div>
</div>
<?php
$categoryId = -1;
if (isset($_GET["category"]) && intval($_GET["category"])) {
$categoryId = intval($_GET["category"]);
switch ($categoryId) {
case 1:
// do query for category id 1
getNews();
break;
case 2:
// do query for category id 2
getEwarehouse();
break;
case 3:
// do query for category id 3
getPartners();
break;
default:
ifnotNumeric();
break;
}
} else {
ifnotSet();
}
?>
Some more general information:
Running laragon 4.0.15 with PHP 7.3.9
Using HeidiSQL 10.2.0.5599
Using PHPStorm 2019.2.2
if you need anymore code examples i can paste them in.

Joomla's Who's Online Counter - How to add thousand separator?

One of my sites frequently has more than 1000 concurrent visitors and just for consistency I want to add a thousands separator to the display so it shows like 1,000.
My initial thought was just to add number_format before the variable holding the guest count but this stops the counter working for some reason.
The function in helper.php counting the guests looks like this:
// show online count
static function getOnlineCount() {
$db = JFactory::getDbo();
// calculate number of guests and users
$result = array();
$user_array = 0;
$guest_array = 0;
$query = $db->getQuery(true);
$query->select('guest, usertype, client_id');
$query->from('#__session');
$query->where('client_id = 0');
$db->setQuery($query);
$sessions = (array) $db->loadObjectList();
if (count($sessions)) {
foreach ($sessions as $session) {
// if guest increase guest count by 1
if ($session->guest == 1 && !$session->usertype) {
$guest_array ++;
}
// if member increase member count by 1
if ($session->guest == 0) {
$user_array ++;
}
}
}
$result['user'] = $user_array;
$result['guest'] = $guest_array;
return $result;
}
And in the template the data is displayed using the following:
<?php if ($showmode == 0 || $showmode == 2) : ?>
<?php $guest = JText::plural('MOD_WHOSONLINE_GUESTS', $count['guest']); ?>
<?php $member = JText::plural('MOD_WHOSONLINE_MEMBERS', $count['user']); ?>
<p><?php echo JText::sprintf('MOD_WHOSONLINE_WE_HAVE', $guest, $member); ?></p>
Where do I put the number_format so the separator is added please?
does this not work?
$guest = JText::plural('MOD_WHOSONLINE_GUESTS',number_format($count['guest'],0,'.',','));

how to pass additional parameter in the url using PHP

How do I pass additional parameter in the url for pagination to work
my existing page link is http://localhost/site/wp-admin/admin.php?page=myPage
how do i create the syntax / logic in PHP to add &pagenum=1 in the url?
currently i have this code
global $wpdb;
$per_page = 6;
$page_query = $wpdb->get_var("SELECT COUNT('id') FROM form");
$pages = ceil($page_query / $per_page);
$currentPage = (isset ($_GET['pagenum'])) ? (int)$_GET['pagenum'] : 1;
$start = ($currentPage -1 ) * $per_page;
$row = $wpdb->get_results("SELECT * FROM form LIMIT $start , $per_page");
//foreach loop here
$pagenum = 1;
$url = "http://localhost/site/wp-admin/admin.php?page=myPage" . "&pagenum=".$pagenum;
Try this::
First build an array of data you want to transfer like--
$data=array(
"param1"=>"value1",
"param2"=>"value2"
);
Then use http_build_queryto convert data to url format!!
$url_data=http_build_query($data);
$target_url="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // your url here
if(strpos($target_url,"?")==false){
$target_url.="?";
}else{
$target_url.="&";
}
$target_url.=$url_data;
$page='MyPage';
$pagenum = 1;
$url = "http://localhost/site/wp-admin/admin.php?page=".$page."&pagenum=".$pagenum;

PHP MYSQL request through JQuery

I have an image gallery, at the moment I limit the results to 10.
What I'm trying to do, through jQuery, is on click of the 'Load more Results' button,
Load the next 10 rows(images) in the database.
at the moment I use a class query.php to make my query call, then in my index.php display the data in a foreach loop.
I was thinking perhaps using the query string to change the limit to rows 10-20 on click but finding difficulty in this.
Any help will be appreciated.
class query.php
public function Query($db_table, $limit) {
$this->db_query = mysql_query("SELECT * FROM $db_table ORDER BY time DESC limit $limit");
while($row = mysql_fetch_array($this->db_query)) {
$rows[] = $row;
}
return $rows;
}
index.php
$lim = $_GET['limit'];
$Results = $Database->Query('info', $lim);
if(is_array($Results)) {?>
foreach ($Results as $Result) {
//echo results
jquery
$("#my_container").load("../lib/class.database.php?limit=10,20" );
Kind regards,
Adam
It's very simple:
1.) You make an AJAX call to your PHP script
$.ajax(
{
url: "get-ajax-images.php",
data: "mode=ajax&start=10&end=20",
success: function() { /* ... */ },
error: function() { /* ... */ }
});
2.) PHP: Load the data from the database based upon start and end
<?php
header("Content-type: application/json");
// Please use intval() to avoid SQL injections!!
$start = isset($_GET['start']) ? intval($_GET['start']) : exit('{"error": true}');
$end = isset($_GET['end']) ? intval($_GET['end']) : exit('{"error": true}');
/* valid start and end? */
if ( $start < 0 || $end < 0 )
exit('{"error": true}');
if ( ($end - $start) <= 0 ||
($end - $start) > 15 )
exit('{"error": true}');
/* All right! */
$sql = "SELECT id, imagepath FROM images LIMIT $start, $end";
$result = mysql_query($sql) or exit('{"error": true}');
$data = array();
while ( $row = mysql_fetch_assoc($result) )
{
$data[] = $row;
}
echo json_encode($data);
Here's the jquery part for you question
http://jsfiddle.net/manuel/e5kXc/
it holds the total amount of loaded results and you could use the var's limit and total for quering the correct results

PHP pagination class

I am looking for a php pagination class, I have used a rather simple one in the past and it is no longer supported.
I was wondering if anyone had any recommendations ?
It seems pointless to build my own when there are probably so many good ones out there.
After more searching I decided that before I use a frameworked version I should fully understand what is involved in a paginator. So I built one myself. Thanks for the suggestions though!
I would suggest Zend_Paginator for the following reasons
It's loosely coupled and doesn't require the entire library.
The ZF community is larger than the PEAR community and is actively running security audits on code, and releasing maintenance versions.
It separates data sources by using the Adapter Pattern, and there are numerous examples of front end UI pattern implementations in the documentation.
Have you tried PEAR::Pager? Usage examples here.
you can try this:
Zebra_Pagination, a generic, Twitter Bootstrap compatible, pagination class written in PHP
check the link below:
http://stefangabos.ro/php-libraries/zebra-pagination
// pagination class
class Pagination
{
// database handle
private $dbh;
// total records in table
private $total_records;
// limit of items per page
private $limit;
// total number of pages needed
private $total_pages;
// first and back links
private $firstBack;
// next and last links
private $nextLast;
// where are we among all pages?
private $where;
public function __construct($dbh) {
$this->dbh = $dbh;
}
// determines the total number of records in table
public function totalRecords($query, array $params)
{
$stmt = $this->dbh->prepare($query);
$stmt->execute($params);
$this->total_records = $stmt->fetchAll(PDO::FETCH_COLUMN)[0];
if (!$this->total_records) {
echo 'No records found!';
return;
}
}
// sets limit and number of pages
public function setLimit($limit)
{
$this->limit = $limit;
// determines how many pages there will be
if (!empty($this->total_records)) {
$this->total_pages = ceil($this->total_records / $this->limit);
}
}
// determine what the current page is also, it returns the current page
public function page()
{
$pageno = (int)(isset($_GET['pageno'])) ? $_GET['pageno'] : $pageno = 1;
// out of range check
if ($pageno > $this->total_pages) {
$pageno = $this->total_pages;
} elseif ($pageno < 1) {
$pageno = 1;
}
// links
if ($pageno > 1) {
// backtrack
$prevpage = $pageno -1;
// 'first' and 'back' links
$this->firstBack = "<div class='first-back'><a href='$_SERVER[PHP_SELF]?pageno=1'>First</a> <a href='$_SERVER[PHP_SELF]?pageno=$prevpage'>Back</a></div>";
}
$this->where = "<div class='page-count'>(Page $pageno of $this->total_pages)</div>";
if ($pageno < $this->total_pages) {
// forward
$nextpage = $pageno + 1;
// 'next' and 'last' links
$this->nextLast = "<div class='next-last'><a href='$_SERVER[PHP_SELF]?pageno=$nextpage'>Next</a> <a href='$_SERVER[PHP_SELF]?pageno=$this->total_pages'>Last</a></div>";
}
return $pageno;
}
// get first and back links
public function firstBack()
{
return $this->firstBack;
}
// get next and last links
public function nextLast()
{
return $this->nextLast;
}
// get where we are among pages
public function where()
{
return $this->where;
}
}
Use:
$pagination = new Pagination($dbh);
$pagination->totalRecords('SELECT COUNT(*) FROM `photos` WHERE `user` = :user', array(':user' => $_SESSION['id']));
$pagination->setLimit(12);
$pagination->page();
echo $pagination->firstBack();
echo $pagination->where();
echo $pagination->nextLast();
Result:
<div class='first-back'><a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=1'>First</a> <a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=3'>Back</a></div>
<div class='page-count'>(Page 4 of 6)</div>
<div class='next-last'><a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=5'>Next</a> <a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=6'>Last</a></div>
public function make_pagination()
{
$total = 0;
$query = "SELECT COUNT(downloads.dn_id) FROM downloads WHERE downloads.dn_type = 'audios'";
$stmt = $this->conn->prepare($query);
$stmt->execute();
$total = $stmt->fetchColumn();
//echo 'row_count = ' . $total;
// How many items to list per page
$limit = 11;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '« ‹' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '› »' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>'.$prevlink.' Page '.$page.' of '.$pages. ' pages'. $nextlink.' </p></div>';
//prepare the page query
$query2 = "
SELECT * FROM downloads, map_artists, song_artists
WHERE map_artists.dn_id = downloads.dn_id
AND song_artists.artist_id = map_artists.artist_id
AND downloads.dn_type = 'audios' GROUP BY downloads.dn_id
ORDER BY downloads.dn_time DESC LIMIT :limit OFFSET :offset ";
$stmt2 = $this->conn->prepare($query2);
$stmt2->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt2->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt2->execute();
// Do we have any results?
if ($stmt2->rowCount() > 0) {
// Define how we want to fetch the results
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt2);
// Display the results
foreach ($iterator as $row) {
echo '<p>'. $row['dn_title'].' - '. $row['artist_name'].'</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
}
Its Very possible that your SQL SELECT statement query may 1000 result into thousand of records. But its is not good idea to display all the results on one page. So we can divide this result into many pages as per requirement as pagination Class .
PAGINATE DATA WITH PAGINATION CLASS VERY EASY
pagination Class helps to generate paging
How To Use Pagination Class
visit this link for more info
http://utlearn.com/2017/02/15/pagination-class-use-pagination-class/
<?php
/**
* #package pagination class
* #version 1.0
*/
/*
#class Name: pagination
#Author: Ahmed Mohamed
#Version: 1.0
#Author URI: https://www.fb.com/100002349977660
#Website URI: http://www.utlearn.com
#class page URI: http://utlearn.com/2017/02/15/pagination-class-use-pagination-class
*/
include_once 'libs/config.php';
include_once 'libs/Database.php';
include_once 'libs/Model.php';
include_once 'libs/pagination.php';
if(!empty($_GET["page"]) and is_numeric($_GET["page"])){
$page = htmlspecialchars(strip_tags($_GET["page"]));
} else {
$page = 1;
}
// news = table name / you page URL / current page / true or false for full query
// its false i just use table name
$pag = new pagination("news", URL."?page=", 3, $page, false);
$pagination = $pag->pagination();
$data = $pag->data();
?>
<news>
<?php foreach($data as $news){ ?>
<header><h1><?=$news->title ?></h1> | <span><?=$news->date ?></span></header>
<div>
<?=$news->content ?>
</div>
<?php } ?>
</news>
<?=$pagination ?>

Categories