set pagination pagenumber as default url - php

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.

Related

How to redirect to you tube using PHP

i have a site it running on a platform called "photo store" its a PHP site. there is image i want some one click that image redirect to my you tube channel but problem is all pages loading from template.so i did some coding and add a few line with if statement first i did only echo that works but when i try to redirect to YouTube it wand load 500 error coming can anyone help me??
this is a code
if(strpos($_SERVER['HTTP_REFERER'],'cart.php') or strpos($_SERVER['HTTP_REFERER'],'index.php')) // Clear the crumbs if coming from the cart or index
unset($_SESSION['crumbsSession']);
try
{
//$useGalleryID = $galleryID; // Original untouched gallery ID
$useMediaID = $mediaID; // Original untouched media ID
if(!$mediaID) // Make sure a media ID was passed
$smarty->assign('noAccess',1);
else
{
if($config['EncryptIDs']) // Decrypt IDs
{
$mediaID = k_decrypt($mediaID);
$useGalleryID = k_encrypt($_SESSION['id']);
}
else
$useGalleryID = $_SESSION['id'];
//echo $mediaID;
idCheck($mediaID); // Make sure ID is numeric
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM {$dbinfo[pre]}media WHERE media_id = '{$mediaID}'";
$mediaInfo = new mediaList($sql);
if($mediaInfo->getRows())
{
if($mediaID==985){
echo $mediaID;
window.location.replace("http://www.youtube.com");
}
else{
$media = $mediaInfo->getSingleMediaDetails('preview');
$galleryIDArray = $mediaInfo->getMediaGalleryIDs(); // Get an array of galleries this media is in
if(#!in_array($mediaID,$_SESSION['viewedMedia'])) // See if media has already been viewed
{
$newMediaViews = $media['views']+1;
mysqli_query($db,"UPDATE {$dbinfo[pre]}media SET views='{$newMediaViews}' WHERE media_id = '{$mediaID}'"); // Update views
$media['views'] = $newMediaViews; // Update the array so the count shown is the new count
$_SESSION['viewedMedia'][] = $mediaID;
}
//print_r($media); exit;
/*
if(!$_SESSION['crumbsSession']) // Get a crumb trail - doesn't work for contibutors yet
{
#$galleryInfo = mysqli_fetch_assoc(mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_galleries WHERE gmedia_id = '{$mediaID}' ORDER BY mg_id LIMIT 1"));
if($galleryInfo['gallery_id'])
{
$galleriesMainPageLink['page'] = "gallery.php?mode=gallery";
$_SESSION['galleriesData'][0]['linkto'] = linkto($galleriesMainPageLink); // Check for SEO
$_SESSION['galleriesData'][0]['name'] = $lang['galleries']; //
$_SESSION['crumbsSession'] = galleryCrumbsFull($galleryInfo['gallery_id']);
}
}
*/
// Check for video sample
$mediaInfo2 = new mediaTools($mediaID);
if($media['dsp_type'] == 'video') // Make sure the DSP type is set to video
{
if($video = $mediaInfo2->getVidSampleInfoFromDB()) // Make sure video file exists
{
$videoCheck = $mediaInfo2->verifyVidSampleExists();
if($videoCheck['status']) { // Make sure the video exists
//print_k($videoCheck); exit;
if($videoCheck['url'] and $config['passVideoThroughPHP'] === false)
$video['url'] = $videoCheck['url']; // Use URL method
else
$video['url'] = $config['settings']['site_url'].'/video.php?mediaID='.$media['encryptedID']; // Use PHP pass-through
//echo $video['url']; exit;
//print_k($video);
$media['videoStatus'] = 1;
$media['videoInfo'] = $video;
} else {
$media['videoStatus'] = 0;
}
}
else
$media['videoStatus'] = 0;
}
else
{
/*
* Get an estimated preview width and height
*/
$sample = $mediaInfo2->getSampleInfoFromDB();
$sampleSize = getScaledSizeNoSource($sample['sample_width'],$sample['sample_height'],$config['settings']['preview_size'],$crop=0);
$media['previewWidth'] = $sampleSize[0];
$media['previewHeight'] = $sampleSize[1];
}
$mediaPrice = getMediaPrice($media); // Get the media price based on the license
$mediaCredits = getMediaCredits($media); // Get the media credits based on the license
// Get category ID - Make sure member has access to category - maybe add this later
$galleryIDArrayFlat = ($galleryIDArray) ? implode(",",$galleryIDArray) : 0;
/*
* Prints *****************************************************************************************************************************
*/
$galleryPrintsResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}prints
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}prints.print_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'prints'
AND ({$dbinfo[pre]}prints.attachment = 'media' OR {$dbinfo[pre]}prints.attachment = 'both')
"
); // Find out which prints are assigned to galleries this photo is in
$galleryPrintsRows = mysqli_num_rows($galleryPrintsResult);
while($galleryPrint = mysqli_fetch_array($galleryPrintsResult))
$printIDArray[] = $galleryPrint['item_id'];
$mediaPrintsResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_prints WHERE media_id = '{$mediaID}'"); // Find what prints have been directly assigned to this photo // GROUP BY print_id
$mediaPrintsRows = mysqli_num_rows($mediaPrintsResult);
//echo $mediaPrintsRows; exit; // Testing
while($mediaPrint = mysqli_fetch_array($mediaPrintsResult))
{
if($mediaPrint['printgrp_id']) // Is a group assignment
{
// Select print groups
$mediaPrintsGroupsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}prints
LEFT JOIN {$dbinfo[pre]}groupids
ON {$dbinfo[pre]}prints.print_id = {$dbinfo[pre]}groupids.item_id
WHERE {$dbinfo[pre]}groupids.group_id = '{$mediaPrint[printgrp_id]}'
AND {$dbinfo[pre]}prints.active = 1
AND {$dbinfo[pre]}prints.deleted = 0
AND {$dbinfo[pre]}groupids.mgrarea = 'prints'
"
);
//$pgRows = mysqli_num_rows($mediaPrintsGroupsResult); // Testing
//echo $pgRows;
while($mediaPrintsGroup = mysqli_fetch_array($mediaPrintsGroupsResult))
$printIDArray[] = $mediaPrintsGroup['print_id'];
}
else
{
$printIDArray[] = $mediaPrint['print_id'];
if($mediaPrint['customized'])
{
$printCustomizedIDs[] = $mediaPrint['print_id']; // Add this ID to the custom array list
$customPrint[$mediaPrint['print_id']] = $mediaPrint; // Get the actual values for the custom item
}
}
}
if($printIDArray)
$printsIDArrayFlat = implode(",",$printIDArray);
else
$printsIDArrayFlat = 0;
// Now that we have the print ID array select the prints that the customer has access to and assign them to smarty
$printsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}prints
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}prints.print_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'prints')
WHERE ({$dbinfo[pre]}prints.print_id IN ({$printsIDArrayFlat}) OR {$dbinfo[pre]}prints.all_galleries = 1)
AND {$dbinfo[pre]}prints.active = 1
AND {$dbinfo[pre]}prints.deleted = 0
AND ({$dbinfo[pre]}prints.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
ORDER BY {$dbinfo[pre]}prints.sortorder
"
);
if($returnRows = mysqli_num_rows($printsResult))
{
while($print = mysqli_fetch_assoc($printsResult))
{
$print['price'] = defaultPrice($print['price']); // Make sure to assign a default price if needed
$print['credits'] = defaultCredits($print['credits']); // Make sure to assign default credits if needed
/*
* Custom Pricing calculations
*/
if(#in_array($print['print_id'],$printCustomizedIDs))
{
$print['price_calc'] = $customPrint[$print['print_id']]['price_calc'];
$print['price'] = defaultPrice($customPrint[$print['print_id']]['price']);
$print['credits'] = defaultCredits($customPrint[$print['print_id']]['credits']);
$print['credits_calc'] = $customPrint[$print['print_id']]['credits_calc'];
$print['quantity'] = $customPrint[$print['print_id']]['quantity'];
}
/*
* Advanced Pricing calculations
*/
switch($print['price_calc'])
{
case 'add':
$print['price'] = $mediaPrice + $print['price'];
break;
case 'sub':
$print['price'] = $mediaPrice - $print['price'];
break;
case 'mult':
$print['price'] = $mediaPrice * $print['price'];
break;
}
switch($print['credits_calc'])
{
case 'add':
$print['credits'] = $mediaCredits + $print['credits'];
break;
case 'sub':
$print['credits'] = $mediaCredits - $print['credits'];
break;
case 'mult':
$print['credits'] = $mediaCredits * $print['credits'];
break;
}
//echo $mediaCredits.'-'.$print['credits'].'-'.$print['credits_calc']."/";
if($print['quantity'] != '0') // Make sure the quantity is other than 0
{
$printsArray[$print['print_id']] = printsList($print,$mediaID);
$optionsResult = mysqli_query($db,"SELECT og_id FROM {$dbinfo[pre]}option_grp WHERE parent_type = 'prints' AND parent_id = '{$print[print_id]}' AND deleted = 0"); // See if there are any options for this item
if(mysqli_num_rows($optionsResult))
{
$printsArray[$print['print_id']]['addToCartLink'] = $printsArray[$print['print_id']]['linkto']; // Workbox popup
$printsArray[$print['print_id']]['directToCart'] = false; // Workbox popup
}
else
{
if($config['EncryptIDs'])
$printsArray[$print['print_id']]['addToCartLink'] = "{$siteURL}/cart.php?mode=add&type=print&id=".$printsArray[$print['print_id']]['encryptedID']."&mediaID={$media[encryptedID]}"; // Direct to cart
else
$printsArray[$print['print_id']]['addToCartLink'] = "{$siteURL}/cart.php?mode=add&type=print&id={$print[print_id]}&mediaID={$media[media_id]}"; // Direct to cart
$printsArray[$print['print_id']]['directToCart'] = true; // Direct to cart
}
}
}
$smarty->assign('printRows',$returnRows);
$smarty->assign('prints',$printsArray);
}
/*
* Digital Files *****************************************************************************************************************************
*/
require_once 'media.details.inc.php';
/*
* Products *****************************************************************************************************************************
*/
$galleryProductsResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}products
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}products.prod_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'products'
AND ({$dbinfo[pre]}products.attachment = 'media' OR {$dbinfo[pre]}products.attachment = 'both')
"
); // Find out which products are assigned to galleries this photo is in
$galleryProductsRows = mysqli_num_rows($galleryProductsResult);
while($galleryProduct = mysqli_fetch_array($galleryProductsResult))
$productIDsArray[] = $galleryProduct['item_id'];
$mediaProductsResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_products WHERE media_id = '{$mediaID}'"); // Find what products have been directly assigned to this photo // GROUP BY prod_id
$mediaProductsRows = mysqli_num_rows($mediaProductsResult);
while($mediaProduct = mysqli_fetch_array($mediaProductsResult))
{
if($mediaProduct['prodgrp_id']) // Is a group assignment
{
// Select product groups
$mediaProductsGroupsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}products
LEFT JOIN {$dbinfo[pre]}groupids
ON {$dbinfo[pre]}products.prod_id = {$dbinfo[pre]}groupids.item_id
WHERE {$dbinfo[pre]}groupids.group_id = '{$mediaProduct[prodgrp_id]}'
AND {$dbinfo[pre]}products.active = 1
AND {$dbinfo[pre]}products.deleted = 0
AND {$dbinfo[pre]}groupids.mgrarea = 'products'
"
);
while($mediaProductsGroup = mysqli_fetch_array($mediaProductsGroupsResult))
$productIDsArray[] = $mediaProductsGroup['prod_id'];
}
else
{
$productIDsArray[] = $mediaProduct['prod_id'];
if($mediaProduct['customized'])
{
$productCustomizedIDs[] = $mediaProduct['prod_id']; // Add this ID to the custom array list
$customProduct[$mediaProduct['prod_id']] = $mediaProduct; // Get the actual values for the custom item
}
}
}
if($productIDsArray)
$productIDsArrayFlat = implode(",",$productIDsArray);
else
$productIDsArrayFlat = 0;
//print_r($productCustomizedIDs); exit;
// Now that we have the product ID array select the products that the customer has access to and assign them to smarty
$productsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}products
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}products.prod_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'products')
WHERE ({$dbinfo[pre]}products.prod_id IN ({$productIDsArrayFlat}) OR {$dbinfo[pre]}products.all_galleries = 1)
AND {$dbinfo[pre]}products.active = 1
AND {$dbinfo[pre]}products.deleted = 0
AND ({$dbinfo[pre]}products.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
ORDER BY {$dbinfo[pre]}products.sortorder
"
);
if($returnRows = mysqli_num_rows($productsResult))
{
while($product = mysqli_fetch_array($productsResult))
{
$product['price'] = defaultPrice($product['price']); // Make sure to assign a default price if needed
$product['credits'] = defaultCredits($product['credits']); // Make sure to assign default credits if needed
/*
* Custom Pricing calculations
*/
if(#in_array($product['prod_id'],$productCustomizedIDs))
{
$product['price_calc'] = $customProduct[$product['prod_id']]['price_calc'];
$product['price'] = defaultPrice($customProduct[$product['prod_id']]['price']);
$product['credits'] = defaultCredits($customProduct[$product['prod_id']]['credits']);
$product['credits_calc'] = $customProduct[$product['prod_id']]['credits_calc'];
$product['quantity'] = $customProduct[$product['prod_id']]['quantity'];
}
/*
* Advanced Pricing calculations
*/
switch($product['price_calc'])
{
case 'add':
$product['price'] = $mediaPrice + $product['price'];
break;
case 'sub':
$product['price'] = $mediaPrice - $product['price'];
break;
case 'mult':
$product['price'] = $mediaPrice * $product['price'];
break;
}
switch($product['credits_calc'])
{
case 'add':
$product['credits'] = $mediaCredits + $product['credits'];
break;
case 'sub':
$product['credits'] = $mediaCredits - $product['credits'];
break;
case 'mult':
$product['credits'] = $mediaCredits * $product['credits'];
break;
}
if($product['quantity'] != '0') // Make sure the quantity is other than 0
{
if($product['product_type'] == '1') // Check if this is a media based product
$productsArray[$product['prod_id']] = productsList($product,$mediaID); // Media based
else
$productsArray[$product['prod_id']] = productsList($product,false); // Stand Alone
$optionsResult = mysqli_query($db,"SELECT og_id FROM {$dbinfo[pre]}option_grp WHERE parent_type = 'products' AND parent_id = '{$product[prod_id]}' AND deleted = 0"); // See if there are any options for this item
if(mysqli_num_rows($optionsResult))
{
$productsArray[$product['prod_id']]['addToCartLink'] = $productsArray[$product['prod_id']]['linkto']; // Workbox popup
$productsArray[$product['prod_id']]['directToCart'] = false; // Workbox popup
}
else
{
if($config['EncryptIDs'])
{
$cartLink = "{$siteURL}/cart.php?mode=add&type=product&id=".$productsArray[$product['prod_id']]['encryptedID'];
if($product['product_type'] == '1') $cartLink .= "&mediaID={$media[encryptedID]}";
$productsArray[$product['prod_id']]['addToCartLink'] = $cartLink; // Direct to cart
}
else
{
$cartLink = "{$siteURL}/cart.php?mode=add&type=product&id={$product[prod_id]}";
if($product['product_type'] == '1') $cartLink .= "&mediaID={$media[media_id]}";
$productsArray[$product['prod_id']]['addToCartLink'] = $cartLink; // Direct to cart
}
$productsArray[$product['prod_id']]['directToCart'] = true; // Direct to cart
}
}
}
$smarty->assign('productRows',$returnRows);
$smarty->assign('products',$productsArray);
}
/*
* Collections *****************************************************************************************************************************
*/
$galleryCollectionsResult = mysqli_query($db,"SELECT item_id FROM {$dbinfo[pre]}item_galleries WHERE mgrarea = 'collections' AND gallery_id IN ({$galleryIDArrayFlat})"); // Find collections from galleries
$galleryCollectionsRows = mysqli_num_rows($galleryCollectionsResult);
if($galleryCollectionsRows)
{
while($galleryCollection = mysqli_fetch_array($galleryCollectionsResult))
$collectionIDs[] = $galleryCollection['item_id'];
}
$mediaCollectionsResult = mysqli_query($db,"SELECT coll_id FROM {$dbinfo[pre]}media_collections WHERE cmedia_id = '{$mediaID}'"); // Find collections this item is directly in
$mediaCollectionsRows = mysqli_num_rows($mediaCollectionsResult);
if($mediaCollectionsRows)
{
while($mediaCollection = mysqli_fetch_array($mediaCollectionsResult))
$collectionIDs[] = $mediaCollection['coll_id'];
}
if($collectionIDs) // Only do if some were found
{
$collectionIDsFlat = implode(',',$collectionIDs);
$collectionsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}collections
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}collections.coll_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'collections')
WHERE {$dbinfo[pre]}collections.active = 1
AND {$dbinfo[pre]}collections.deleted = 0
AND ({$dbinfo[pre]}collections.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
AND ({$dbinfo[pre]}collections.quantity = '' OR {$dbinfo[pre]}collections.quantity > '0')
AND {$dbinfo[pre]}collections.coll_id IN ({$collectionIDsFlat})
ORDER BY {$dbinfo[pre]}collections.sortorder
"
); // Select collections that member has access to
if($returnRows = mysqli_num_rows($collectionsResult))
{
while($collections = mysqli_fetch_array($collectionsResult))
{
$collectionsArray[$collections['coll_id']] = collectionsList($collections);
$collectionsWithAccess[] = $collections['coll_id'];
}
$smarty->assign('collectionRows',$returnRows);
$smarty->assign('collections',$collectionsArray);
}
}
/*
* Packages *****************************************************************************************************************************
*/
/*
$galleryPackagesResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}packages
WHERE all_galleries = 1
AND (attachment = 'media' OR attachment = 'both')
"
); // Find packages that are assigned to all galleries and are attached to media or both
$galleryPackagesRows = mysqli_num_rows($galleryPackagesResult);
while($galleryPackage = mysqli_fetch_array($galleryPackagesResult))
$packageIDsArray[] = $galleryPackage['pack_id'];
*/
$galleryPackagesResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}packages
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}packages.pack_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'packages'
AND ({$dbinfo[pre]}packages.attachment = 'media' OR {$dbinfo[pre]}packages.attachment = 'both')
"
); // Find out which packages are assigned to galleries this photo is in or all galleries and attached to media or both
$galleryPackagesRows = mysqli_num_rows($galleryPackagesResult);
while($galleryPackage = mysqli_fetch_array($galleryPackagesResult))
$packageIDsArray[] = $galleryPackage['item_id'];
//print_r($packageIDsArray); // Testing
$mediaPackagesResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_packages
window.location.replace("http://www.youtube.com"); is wrong
use thins:
header("Location: http://www.youtube.com");
exit;
Remember that this must be called before any actual output is sent

PHP videos multiple pages doesn't work correctly

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!

php recursive function not working correctly

i have a categories table
(id=1 , name=Hand made, parent=0)
(id=2 , name=Factory made, parent=0)
(id=3 , name=chairs, parent=1)
(id=4 , name=tabels, parent=1)
(id=5 , name=old chairs, parent=3)
at the menu if visitor clicked on category OLD CHAIRS , will go to page
products.php?category_id = 5
then at this page i need to know what is the main category_id , which should be HAND MADE with category_id=1
so at this page i want to say
if isset($_REQUEST['category_id']){
do the function till find the main parent,
$mainparentid = main parent category_id
}else { $mainparentid = '';
} echo $mainparentid;
here is my PHP Code
if (isset($_REQUEST['category_id'])) {
function getParent($id) {
global $connection;
$query_rsCategoryId = "SELECT * FROM categories
WHERE category_id = '".$_REQUEST['category_id']."'";
$rsCategoryId = mysql_query($query_rsCategoryId, $connection);
$row_rsCategoryId = mysql_fetch_assoc($rsCategoryId);
$parent = $row_rsCategoryId['category_parent'];
if (mysql_num_rows($rsCategoryId) < 1) {
// Error handling, entry with id $id not found
return null;
}
if ($parent == 0) {
return $id;
} else {
return getParent($parent);
}
}
$mainparentid = getParent($id);
}else {
$mainparentid ='none';
}
echo $mainparentid ;
You always input ID of the category from $_REQUEST. Change line:
WHERE category_id = '".$_REQUEST['category_id']."'";
to:
WHERE category_id = '".$id."'";
You are using parent id from request instead of given via function parameter
// notice $id instead of $_REQUEST['category_id']
$query_rsCategoryId = "SELECT * FROM categories WHERE category_id = '{$id}'";

codeigniter pagination with dynamic url structure

In my codeigniter app i have an article module, which has three categories,
primary category
secondary category
tertiary category
list of articles
Now the first page shows an accordion with the heirarchy above except the list of articles, the user can click on expand or click on a category name directly.
So if a user clicks on primary category name all the articles will be listed paginated based on codeigniter's inbuilt pagination library.
Likewise if a tertiary category is clicked articles in that alone will be listed. The problem is all the articles listing is handled by a single function and hence i have a route like this.
$route['article/(:any)/(:any)/(:any)/(:any)'] = "articles/articles/show_article/$4";
$route['article/(:any)/(:any)/(:any)'] = "articles/articles/find_type/$3";
$route['article/(:any)/(:any)'] = "articles/articles/find_type/$2";
$route['article/(:any)'] = "articles/articles/find_type/$1";
and my find_type method is
function find_type($str)
{
$rawstr = $str;
$str = deurl($str);
$ch = 1;
$id = 0;
$query = $this->db->get_where("articles_primary",array("primary_name"=>$str));
if($query->num_rows==1) {
$ch = 1;
$id = $query->row('id');
}
$query = $this->db->get_where("articles_secondary",array("secondary_name"=>$str));
if($query->num_rows==1) {
$ch = 2;
$id = $query->row('id');
}
$query = $this->db->get_where("articles_tertiary",array("tertiary_name"=>$str));
if($query->num_rows==1) {
$ch = 3;
$id = $query->row('id');
}
$query = $this->db->get_where("articles_list",array("url_title"=>$rawstr));
if($query->num_rows==1) {
$ch = 4;
}
switch ($ch)
{
case 1:
$this->show_articles_list($id,"primary",$rawstr);
break;
case 2:
$this->show_articles_list($id,"secondary",$rawstr);
break;
case 3:
$this->show_articles_list($id,"tertiary",$rawstr);
break;
case 4:
$this->show_article($rawstr);
break;
}
}
and finally my list articles is
function show_articles_list($id,$tbl,$rawstr)
{
$query = $this->db->get_where("articles_list",array($tbl."_id"=>$id));
$this->load->library('pagination');
$config['base_url'] = current_url();
$config['total_rows'] = $query->num_rows;
$config['per_page'] = 9;
$this->pagination->initialize($config);
$page = $this->uri->segment(3);
if($page=="") { $page = 0; }
$this->db->limit(9,$page);
$data["query"] = $this->db->get_where("articles_list",array($tbl."_id"=>$id));
$this->template->write_view('maincontent', 'articles/articles_list',$data);
//$this->template->write_view('subcontent', 'articles/related_articles',$data);
$this->template->write("title","Laws",true);
$this->template->write_view('rightcontent','general/include/query_document_tab');
$this->template->render();
}
as you can see the routes are based on uri segments and hence the pagination is not working. Is there anyway i can tweak the pagination to work with the current setup i have?
How about adding another parameter to the functions and changing the routes file accordingly:
function find_type($str, $page=0){
...
$this->show_articles_list($id,"primary",$rawstr, $page);
etc...
...
}
function show_articles_list($id,$tbl,$rawstr,$page)...
Routes:
$route['article/(:any)/(:any)/(:any)/(:any)'] = "articles/articles/show_article/$4/4";
$route['article/(:any)/(:any)/(:any)'] = "articles/articles/find_type/$3/3";
$route['article/(:any)/(:any)'] = "articles/articles/find_type/$2/2";
$route['article/(:any)'] = "articles/articles/find_type/$1/1";
You'd use that parameter to denote the uri segment for pagination.
OR
You can just use $this->uri->total_segments().

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