Paging for directory listing in php - php

I'm trying to get the paging for directory listing script.
Here is the original code for the function.
This function list all the mp3 files in the directory and some file information.
$songs is holding the array infomation
original code
function htmlSongs(&$tmpl, $path_raw, $songs, $custom_pls = false, $c_pls_arr = null, $lofi = false, $various, $dir_write, $song_ratings) {
global $z_url_base, $z_self, $z_img_play, $z_img_lofi, $z_img_down,
$z_admin, $z_img_new, $z_img_edit, $z_self_raw, $zc, $z_db,$img_src;
$i = 0;
$check_boxes = false;
$diff = $zc['new_time']*60*60*24;
if (($z_admin && $zc['cache']) || ($zc['playlists'] && $zc['session_pls']) || $zc['play_sel'] || $zc['cmp_sel']) {
$check_boxes = true;
}
$tmpl = str_replace('{$songs_form_opts}', "name='songs' method='post' action='${z_self}p=$path_raw'", $tmpl);
$temp_section = tmpGetSect($tmpl, "SONGROW");
$html = "";
$rating = ($z_db && $zc['rating_files']);
foreach ($songs as $song => $opts) {
$temp_song = $temp_section;
$valign = ($opts['blurb']) ? "valign='top'" : "";
$song_raw = getURLencodedPath($song);
$song_title = formatSongTitle(basename($song));
$temp_song = str_replace('{$row}', $i, $temp_song);
$temp_song = str_replace('{$valign}', $valign, $temp_song);
$t_blurb = ($dir_write) ? "${opts['blurb']} <a href='${z_self_raw}&pl=".getURLencodedPath(basename($song))."&l=22&m=3'>$z_img_edit</a>" : $opts['blurb'];
$temp_song = str_replace('{$song_blurb}', $t_blurb, $temp_song);
$t_song_opts = "";
$remote = false;
if ($zc['fake'] && isset($opts['fake'])) {
$fi = ($zc['mp3_info']) ? "<td colspan='4'> </td>" : "";
$temp_song = tmpDelSec($temp_song,"SONGINFO", $fi);
$fi = ($rating) ? "<td colspan='2'> </td>" : "";
$temp_song = tmpDelSec($temp_song,"SONGVOTE", $fi);
$temp_song = tmpDelSec($temp_song,"SONGRATING");
$t_song_title = preg_replace("/\.(".$zc['fake_ext'].")$/i","",$song_title);
} else {
$url_play = $url_end = "";
if ($zc['mp3_info'] || $zc['mp3_id3']) {
if ($zc['remote'] && preg_match("/\.(".$zc['remote_ext'].")$/i", $song)) {
$mp3 = new remoteFile($zc['mp3_dir']."/$song", $zc['mp3_info'], $zc['mp3_id3']);
$remote = true;
} else {
$mp3 = new mp3($zc['mp3_dir']."/$song", $zc['mp3_info'], $zc['mp3_id3'], $zc['mp3_info_faster']);
}
}
if ($check_boxes) {
$checked = ($custom_pls && in_array($song, $c_pls_arr)) ? " checked='checked'" : "";
$t_song_opts .= "<input type='checkbox' name='mp3s[]' value='$song_raw'$checked /> ";
} else {
$t_song_opts .= " ";
}
if ($zc['download']) {
if ($remote) {
if (isset($mp3->download)) $t_song_opts .= "<a href='".$mp3->download."'>$z_img_down</a> ";
} else {
$surl = ($zc['stream_int']) ? "${z_self}l=12&p=$song_raw" : "$z_url_base/".getURLencodedPath2($song);
$t_song_opts .= "<a href='$surl&Oauth=$newssid'>$z_img_down</a> ";
}
}
if ($zc['play']) {
$url_play = "<a type=\"audio/mpeg\" title='$song_title' href='$mp3->url' >";
$url_end = "</a>";
if($mp3->url != ""){
$t_song_opts .= "$url_play </a> ";
}else{
$t_song_opts .= "";
}
}
if ($zc['low']) {
$tmp = " <a href='${z_self}l=8&p=";
if (isset($opts['lofi'])) {
$t_song_opts .= "$tmp".preg_replace("/\.(".$zc['ext_mus'].")$/i", $zc['low_suf'].".$1", $song_raw).
"&m=1'>$z_img_lofi</a> ";
} elseif($zc['resample'] && preg_match("/\.(".$zc['ext_enc'].")$/i", $song)) {
$t_song_opts .= "$tmp$song_raw&m=6'>$z_img_lofi</a> ";
}
}
if ($zc['new_highlight'] && isset($opts['mtime']) && ($now - $opts['mtime'] < $diff)) {
if ($zc['new_img']) {
$new_end = $z_img_new;
$new_beg = "";
} else {
$new_beg = $zc['new_beg'];
$new_end = $zc['new_end'];
}
} else {
$new_beg = $new_end = "";
}
$t_song_title = "$new_beg";
if ($zc['mp3_id3'] && $mp3->tag) {
if ($various && !empty($mp3->artist)) $t_song_title .= "$mp3->artist - ";
$t_song_title .= $mp3->title;
} else {
$subdir_images = "";
$t_song_title .= "$song_title";
}
$t_song_titles = "$new_beg";
if ($zc['mp3_id3'] && $mp3->tag) {
if ($various && !empty($mp3->artist)) $t_song_title .= "$mp3->artist - ";
$t_song_titles .= $mp3->title;
} else {
//$t_song_titles .= "<a href='$surl' type='audio/mpeg' title='$song_title'><img src='$img_src' style='display:none' /></a>";
$t_song_titles .= "";
}
$t_song_title .= "$new_end";
if ($zc['mp3_info']) {
if ($mp3->info == 1) {
$t_time = $mp3->time;
$t_bitrate = "$mp3->bitrate kbps";
$t_frequency = round($mp3->frequency/1000,1). " kHz";
$t_size = sprintf("%.2f", round($mp3->filesize/1000000,2))." Mb";
} else {
$t_size = (!$remote) ? sprintf("%.2f", round($mp3->filesize/1000000,2))." Mb" : " ";
$t_time = $t_bitrate = $t_frequency = " ";
}
$temp_song = str_replace('{$song_time}', $t_time, $temp_song);
$temp_song = str_replace('{$song_bitrate}', $t_bitrate, $temp_song);
$temp_song = str_replace('{$song_frequency}', $t_frequency, $temp_song);
$temp_song = str_replace('{$song_size}', $t_size, $temp_song);
} else {
$temp_song = tmpDelSec($temp_song,"SONGINFO");
}
if ($rating) {
$temp_song = str_replace('{$song_vote}', htmlVote($song), $temp_song);
$rating = (!empty($song_ratings) && isset($song_ratings[$song])) ? htmlVoteFormat($song_ratings[$song]) : " ";
$temp_song = str_replace('{$song_rating}', $rating, $temp_song);
} else {
$temp_song = tmpDelSec($temp_song,"SONGVOTE");
$temp_song = tmpDelSec($temp_song,"SONGRATING");
}
}
$temp_song = str_replace('{$song_title}', $t_song_title, $temp_song);
$temp_song = str_replace('{$song_titles}', $t_song_titles, $temp_song);
$temp_song = str_replace('{$song_opts}', $t_song_opts, $temp_song);
$temp_song = str_replace('{$pageshtml}', $t_pageshtml, $temp_song);
$html .= $temp_song;
$i = ++$i % 2;
}
$tmpl = tmpDelSec($tmpl,"SONGROW",$html);
$t_so_check = $t_so_sel = $t_so_pls = "";
if ($z_admin && $zc['cache']) {
$submit = ($custom_pls) ? _ZUPDATECUSTOM : _ZCREATECUSTOM;
$t_so_check .= "<input type='submit' value='$submit ' onClick=\"SubmitForm('songs','&l=3&z=3',false);\"/>";
}
if ($check_boxes) {
$t_so_check .= " "._ZCHECK.": "._ZALL." | ".
""._ZNONE."";
if ($zc['play_sel'] || $zc['cmp_sel']) {
$url_beg2 = " <a class='htrack' type='audio/mpeg' href=\"javascript:CheckIt('songs',";
$t_so_sel .= _ZSELECTED.": ";
$err = _ZERR_SEL;
if ($zc['play'] && $zc['play_sel']) { $t_so_sel .= "$url_beg2'${z_self}l=8&m=7',true,'$err');\">$z_img_play</a>"; }
if ($lofi) { $t_so_sel .= "$url_beg2'${z_self}l=8&m=7&lf=true',true,'$err');\">$z_img_lofi</a>"; }
if ($zc['download'] && $zc['cmp_sel']) { $t_so_sel .= "$url_beg2'&l=8&m=8',false,'$err');\">$z_img_down</a>"; }
}
}
$title = substr($path_raw,strrpos($path_raw,"/")+1);
$t_so_pls = ($zc['playlists']) ? htmlPlaylistFormElements('songs') : " ";
$tmpl = str_replace('{$row}',$i, $tmpl);
$tmpl = str_replace('{$so_check}',$t_so_check, $tmpl);
$tmpl = str_replace('{$so_select}',$t_so_sel, $tmpl);
$tmpl = str_replace('{$so_playlist}',$t_so_pls, $tmpl);
$tmpl = str_replace('{$movie_title}', $title, $tmpl);
Here is the some workaround to get the paging, this function is working but it's not showing the file information such as file name, time, size
This is the edited code.
function htmlSongs(&$tmpl, $path_raw, $songs, $custom_pls = false, $c_pls_arr = null, $lofi = false, $various, $dir_write, $song_ratings) {
global $z_url_base, $z_self, $z_img_play, $z_img_lofi, $z_img_down,
$z_admin, $z_img_new, $z_img_edit, $z_self_raw, $zc, $z_db,$img_src;
$i = 0;
$check_boxes = false;
$diff = $zc['new_time']*60*60*24;
if (($z_admin && $zc['cache']) || ($zc['playlists'] && $zc['session_pls']) || $zc['play_sel'] || $zc['cmp_sel']) {
$check_boxes = true;
}
$tmpl = str_replace('{$songs_form_opts}', "name='songs' method='post' action='${z_self}p=$path_raw'", $tmpl);
$temp_section = tmpGetSect($tmpl, "SONGROW");
$html = "";
$rating = ($z_db && $zc['rating_files']);
$i = $stat_prev = 0;
$p = 1;
$currents = htmlspecialchars($_GET['showpage']);
$pages = array_chunk($songs, 10);
$t_pageshtml .= '<center>Page '.($currents+1).' of '.count($pages).' <br>Pages: ';
for($i=1; $i< count($pages)+1; $i++){
$t_pageshtml .= ''.$i.' ';
}
$t_pageshtml .= '</center>';
$pgkey = (int)htmlspecialchars($_GET['showpage']);
$pages[$pgkey];
foreach ($pages[$pgkey] as $song => $opts) {
$temp_song = $temp_section;
$valign = ($opts['blurb']) ? "valign='top'" : "";
$song_raw = getURLencodedPath($song);
$song_title = formatSongTitle(basename($song));
$temp_song = str_replace('{$row}', $i, $temp_song);
$temp_song = str_replace('{$valign}', $valign, $temp_song);
$t_blurb = ($dir_write) ? "${opts['blurb']} <a href='${z_self_raw}&pl=".getURLencodedPath(basename($song))."&l=22&m=3'>$z_img_edit</a>" : $opts['blurb'];
$temp_song = str_replace('{$song_blurb}', $t_blurb, $temp_song);
$t_song_opts = "";
$remote = false;
if ($zc['fake'] && isset($opts['fake'])) {
$fi = ($zc['mp3_info']) ? "<td colspan='4'> </td>" : "";
$temp_song = tmpDelSec($temp_song,"SONGINFO", $fi);
$fi = ($rating) ? "<td colspan='2'> </td>" : "";
$temp_song = tmpDelSec($temp_song,"SONGVOTE", $fi);
$temp_song = tmpDelSec($temp_song,"SONGRATING");
$t_song_title = preg_replace("/\.(".$zc['fake_ext'].")$/i","",$song_title);
} else {
$url_play = $url_end = "";
if ($zc['mp3_info'] || $zc['mp3_id3']) {
if ($zc['remote'] && preg_match("/\.(".$zc['remote_ext'].")$/i", $song)) {
$mp3 = new remoteFile($zc['mp3_dir']."/$song", $zc['mp3_info'], $zc['mp3_id3']);
$remote = true;
} else {
$mp3 = new mp3($zc['mp3_dir']."/$song", $zc['mp3_info'], $zc['mp3_id3'], $zc['mp3_info_faster']);
}
}
if ($check_boxes) {
$checked = ($custom_pls && in_array($song, $c_pls_arr)) ? " checked='checked'" : "";
$t_song_opts .= "<input type='checkbox' name='mp3s[]' value='$song_raw'$checked /> ";
} else {
$t_song_opts .= " ";
}
if ($zc['download']) {
if ($remote) {
if (isset($mp3->download)) $t_song_opts .= "<a href='".$mp3->download."'>$z_img_down</a> ";
} else {
$surl = ($zc['stream_int']) ? "${z_self}l=12&p=$song_raw" : "$z_url_base/".getURLencodedPath2($song);
$t_song_opts .= "<a href='$surl&Oauth=$newssid'>$z_img_down</a> ";
}
}
if ($zc['play']) {
$url_play = "<a type=\"audio/mpeg\" title='$song_title' href='$mp3->url' >";
$url_end = "</a>";
if($mp3->url != ""){
$t_song_opts .= "$url_play </a> ";
}else{
$t_song_opts .= "";
}
}
if ($zc['low']) {
$tmp = " <a href='${z_self}l=8&p=";
if (isset($opts['lofi'])) {
$t_song_opts .= "$tmp".preg_replace("/\.(".$zc['ext_mus'].")$/i", $zc['low_suf'].".$1", $song_raw).
"&m=1'>$z_img_lofi</a> ";
} elseif($zc['resample'] && preg_match("/\.(".$zc['ext_enc'].")$/i", $song)) {
$t_song_opts .= "$tmp$song_raw&m=6'>$z_img_lofi</a> ";
}
}
if ($zc['new_highlight'] && isset($opts['mtime']) && ($now - $opts['mtime'] < $diff)) {
if ($zc['new_img']) {
$new_end = $z_img_new;
$new_beg = "";
} else {
$new_beg = $zc['new_beg'];
$new_end = $zc['new_end'];
}
} else {
$new_beg = $new_end = "";
}
$t_song_title = "$new_beg";
if ($zc['mp3_id3'] && $mp3->tag) {
if ($various && !empty($mp3->artist)) $t_song_title .= "$mp3->artist - ";
$t_song_title .= $mp3->title;
} else {
$subdir_images = "";
$t_song_title .= "$song_title";
}
$t_song_titles = "$new_beg";
if ($zc['mp3_id3'] && $mp3->tag) {
if ($various && !empty($mp3->artist)) $t_song_title .= "$mp3->artist - ";
$t_song_titles .= $mp3->title;
} else {
//$t_song_titles .= "<a href='$surl' type='audio/mpeg' title='$song_title'><img src='$img_src' style='display:none' /></a>";
$t_song_titles .= "";
}
$t_song_title .= "$new_end";
if ($zc['mp3_info']) {
if ($mp3->info == 1) {
$t_time = $mp3->time;
$t_bitrate = "$mp3->bitrate kbps";
$t_frequency = round($mp3->frequency/1000,1). " kHz";
$t_size = sprintf("%.2f", round($mp3->filesize/1000000,2))." Mb";
} else {
$t_size = (!$remote) ? sprintf("%.2f", round($mp3->filesize/1000000,2))." Mb" : " ";
$t_time = $t_bitrate = $t_frequency = " ";
}
$temp_song = str_replace('{$song_time}', $t_time, $temp_song);
$temp_song = str_replace('{$song_bitrate}', $t_bitrate, $temp_song);
$temp_song = str_replace('{$song_frequency}', $t_frequency, $temp_song);
$temp_song = str_replace('{$song_size}', $t_size, $temp_song);
} else {
$temp_song = tmpDelSec($temp_song,"SONGINFO");
}
if ($rating) {
$temp_song = str_replace('{$song_vote}', htmlVote($song), $temp_song);
$rating = (!empty($song_ratings) && isset($song_ratings[$song])) ? htmlVoteFormat($song_ratings[$song]) : " ";
$temp_song = str_replace('{$song_rating}', $rating, $temp_song);
} else {
$temp_song = tmpDelSec($temp_song,"SONGVOTE");
$temp_song = tmpDelSec($temp_song,"SONGRATING");
}
}
$temp_song = str_replace('{$song_title}', $t_song_title, $temp_song);
$temp_song = str_replace('{$song_titles}', $t_song_titles, $temp_song);
$temp_song = str_replace('{$song_opts}', $t_song_opts, $temp_song);
$temp_song = str_replace('{$pageshtml}', $t_pageshtml, $temp_song);
$html .= $temp_song;
$i = ++$i % 2;
$p++;
}
$tmpl = tmpDelSec($tmpl,"SONGROW",$html);
//$t_pageshtml = 'UUUU';
$t_so_check = $t_so_sel = $t_so_pls = "";
if ($z_admin && $zc['cache']) {
$submit = ($custom_pls) ? _ZUPDATECUSTOM : _ZCREATECUSTOM;
$t_so_check .= "<input type='submit' value='$submit ' onClick=\"SubmitForm('songs','&l=3&z=3',false);\"/>";
}
if ($check_boxes) {
$t_so_check .= " "._ZCHECK.": "._ZALL." | ".
""._ZNONE."";
if ($zc['play_sel'] || $zc['cmp_sel']) {
$url_beg2 = " <a class='htrack' type='audio/mpeg' href=\"javascript:CheckIt('songs',";
$t_so_sel .= _ZSELECTED.": ";
$err = _ZERR_SEL;
if ($zc['play'] && $zc['play_sel']) { $t_so_sel .= "$url_beg2'${z_self}l=8&m=7',true,'$err');\">$z_img_play</a>"; }
if ($lofi) { $t_so_sel .= "$url_beg2'${z_self}l=8&m=7&lf=true',true,'$err');\">$z_img_lofi</a>"; }
if ($zc['download'] && $zc['cmp_sel']) { $t_so_sel .= "$url_beg2'&l=8&m=8',false,'$err');\">$z_img_down</a>"; }
}
}
$title = substr($path_raw,strrpos($path_raw,"/")+1);
$t_so_pls = ($zc['playlists']) ? htmlPlaylistFormElements('songs') : " ";
$tmpl = str_replace('{$row}',$i, $tmpl);
$tmpl = str_replace('{$so_check}',$t_so_check, $tmpl);
$tmpl = str_replace('{$so_select}',$t_so_sel, $tmpl);
$tmpl = str_replace('{$so_playlist}',$t_so_pls, $tmpl);
$tmpl = str_replace('{$movie_title}', $title, $tmpl);
$tmpl = str_replace('{$pages_html}', $t_pageshtml, $tmpl);
}
This is the code for paging
$i = $stat_prev = 0;
$p = 1;
$currents = htmlspecialchars($_GET['showpage']);
$pages = array_chunk($songs, 10);
$t_pageshtml .= '<center>Page '.($currents+1).' of '.count($pages).' <br>Pages: ';
for($i=1; $i< count($pages)+1; $i++){
$t_pageshtml .= ''.$i.' ';
}
$t_pageshtml .= '</center>';
$pgkey = (int)htmlspecialchars($_GET['showpage']);
$pages[$pgkey];
i think something wrong here
original code
foreach ($songs as $song => $opts)
edited code
foreach ($pages[$pgkey] as $song => $opts) {
OK
I solved the problem my self.
here is the solution
i use array_slice
$i = $stat_prev = 0;
$p = 1;
$currents = htmlspecialchars($_GET['showpage']);
$pages = array_chunk($songs, 10);
$t_pageshtml .= '<center>Page '.($currents+1).' of '.count($pages).' <br>Pages: ';
for($i=1; $i< count($pages)+1; $i++){
$t_pageshtml .= ''.$i.' ';
}
$t_pageshtml .= '</center>';
$pgkey = (int)htmlspecialchars($_GET['showpage']);
$songs = array_slice($songs, $pgkey."0",10);
foreach ($songs as $song => $opts ) {

You can "paginate" any one-dimensional array by using the array_chunk function:
$pages = array_chunk($songs, $perPage = 10);
$pageCount = count($pages);
$currentPageSongs = $pages[$page-1]; # pages are zero-based

Related

Save file on specific directory inside server instead of downloading the file

I'm trying to change this below script that will works and save same file but inside server internal location instead of like it is doing now save file and then upload to my destination.
<?php
session_start();
include("includes/config.inc2.php");
#ini_set('display_errors','Off');
$quantity_store_query = ''; $quantity_store_query1 = '';
if(isset($_REQUEST['store_id']) && $_REQUEST['store_id'] != '')
{
$get_t = mysql_fetch_array(mysql_query("select quantity_store_id from tbl_website where `store_id` = '".$_REQUEST['store_id']."'"));
$quantity_store_query = " pq.quantity_store_id = '".$get_t['quantity_store_id']."' and ";
$quantity_store_query1 = " quantity_store_id = '".$get_t['quantity_store_id']."' and ";
$get_cur = mysql_fetch_array(mysql_query("SELECT currencies_id FROM currencies WHERE code = (SELECT currency FROM tbl_store WHERE store_id = {$_REQUEST['store_id']})"));
$currency = $get_cur['currencies_id'];
}
if(isset($_REQUEST['lowstock']) && $_REQUEST['lowstock'] != '')
{
define("MINI_ITMS_STOCK",5);
$data='';
$csv_output="";
$refundquery = mysql_query("select p.product_name,p.product_code,p.product_desc,p.weight,p.was_price,p.quantity,p.id,p.created_dt from product as p,product_quantity as pq where ".$quantity_store_query." p.id = pq.product_id and pq.`quantity` <= '".MINI_ITMS_STOCK."' group by pq.product_id order by p.created_dt") or die(mysql_error());
if(mysql_num_rows($refundquery) > 0)
{
$row1 = array("Item Name", "Item Code", "Description", "Weight", "Colour", "Size", "Wholesale Price", "Image1", "Image2", "Image3", "Image4", "Image5", "Quantity");
foreach ($row1 as $value1 )
{
$data .= $value1."\t";
}
$data .= "\n";
for($p=0;$p<mysql_num_rows($refundquery);$p++)
{
$orderinfo = mysql_fetch_array($refundquery);
$prod_id = $orderinfo['id'];
$product_name = stripslashes($orderinfo['product_name']);
$product_code = stripslashes($orderinfo['product_code']);
$product_desc = strip_tags(stripslashes($orderinfo['product_desc']));
$weight = stripslashes($orderinfo['weight']);
$was_price = get_table_data("product_price","price","product_id=".$prod_id." AND store_id=".$_REQUEST['store_id'] . " AND currencies_id = $currency");
$colour_name = 'N/A';
$size_name = 'N/A';
$quantity = $info['quantity'];
$barcode = $info['barcode'];
$psql = mysql_query("SELECT * FROM `product_quantity` where ".$quantity_store_query1." product_id = '$prod_id' and `quantity` <= '".MINI_ITMS_STOCK."' LIMIT 12") or die(mysql_error());
if(mysql_num_rows($psql) > 0)
{
for($k=0;$k<mysql_num_rows($psql);$k++)
{
$kinfo = mysql_fetch_array($psql);
$colour_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['color_id']);
$size_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['size_id']);
$images = get_image_data($prod_id,$kinfo['color_id']);
$quantity = $kinfo['quantity'];
$barcode = $kinfo['barcode'];
if($quantity <= MINI_ITMS_STOCK)
{
$export=array($product_name,$product_code,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}
$csv_output .= "\n";
}
}
}
else
{
$p_sql = mysql_query("SELECT * FROM `product` where id = $prod_id and quantity <= ".MINI_ITMS_STOCK." and is_color = 0 and is_size = 0");
if(mysql_num_rows($p_sql) > 0)
{
$kinfo = mysql_fetch_array($p_sql);
$images = get_image_data($prod_id,0);
$export=array($product_name,$product_code,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}$csv_output .= "\n";
}
}
}
$data = str_replace("\r","",$data);
$to_date = date("d-m-y-h-i-s");
$excel_name = "Low_stock_".$to_date;
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"".$excel_name.".xls\"");
header("Pragma: no-cache");
header("Expires: 0");
print $data.$csv_output;
exit;
}
}
if(isset($_REQUEST['outofstock']) && $_REQUEST['outofstock'] != '')
{
define("MINI_ITMS_STOCK",0);
$data='';
$csv_output="";
$refundquery = mysql_query("select p.product_name,p.product_code,p.product_desc,p.weight,p.was_price,p.quantity,p.id,p.created_dt from product as p,product_quantity as pq where ".$quantity_store_query." p.id = pq.product_id and pq.`quantity` <= '".MINI_ITMS_STOCK."' group by pq.product_id order by p.created_dt") or die(mysql_error());
if(mysql_num_rows($refundquery) > 0)
{
$row1 = array("Item Name", "Item Code", "Barcode", "Description", "Weight", "Colour", "Size", "Wholesale Price", "Image1", "Image2", "Image3", "Image4", "Image5", "Quantity");
foreach ($row1 as $value1 )
{
$data .= $value1."\t";
}
$data .= "\n";
for($p=0;$p<mysql_num_rows($refundquery);$p++)
{
$orderinfo = mysql_fetch_array($refundquery);
$prod_id = $orderinfo['id'];
$product_name = stripslashes($orderinfo['product_name']);
$product_code = stripslashes($orderinfo['product_code']);
$product_desc = strip_tags(stripslashes($orderinfo['product_desc']));
$weight = stripslashes($orderinfo['weight']);
$was_price = get_table_data("product_price","price","product_id=".$prod_id." AND store_id=".$_REQUEST['store_id'] . " AND currencies_id = $currency");
$colour_name = 'N/A';
$size_name = 'N/A';
$quantity = $info['quantity'];
$barcode = $info['barcode'];
$psql = mysql_query("SELECT * FROM `product_quantity` where ".$quantity_store_query1." product_id = '$prod_id' and `quantity` <= '".MINI_ITMS_STOCK."'") or die(mysql_error());
if(mysql_num_rows($psql) > 0)
{
for($k=0;$k<mysql_num_rows($psql);$k++)
{
$kinfo = mysql_fetch_array($psql);
$colour_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['color_id']);
$size_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['size_id']);
$images = get_image_data($prod_id,$kinfo['color_id']);
$quantity = $kinfo['quantity'];
$barcode = $kinfo['barcode'];
if($quantity <= MINI_ITMS_STOCK)
{
$export=array($product_name,$product_code,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}
$csv_output .= "\n";
}
}
}
else
{
$p_sql = mysql_query("SELECT * FROM `product` where id = $prod_id and quantity <= ".MINI_ITMS_STOCK." and is_color = 0 and is_size = 0");
if(mysql_num_rows($p_sql) > 0)
{
$kinfo = mysql_fetch_array($p_sql);
$images = get_image_data($prod_id,0);
$export=array($product_name,$product_code,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}$csv_output .= "\n";
}
}
}
$data = str_replace("\r","",$data);
$to_date = date("d-m-y-h-i-s");
$excel_name = "Out_Of_stock_".$to_date;
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"".$excel_name.".xls\"");
header("Pragma: no-cache");
header("Expires: 0");
print $data.$csv_output;
exit;
}
}
if(isset($_REQUEST['stock']) && $_REQUEST['stock'] != '')
{
define("MINI_ITMS_STOCK",'-1');
$data='';
$csv_output="";
$refundquery = mysql_query("select p.main_category_name,p.sub_category_name,p.item_collection,p.product_name,p.product_code,p.product_desc,p.weight,p.was_price,p.quantity,p.id,p.created_dt from product as p,product_quantity as pq where ".$quantity_store_query." p.id = pq.product_id and pq.`quantity` >= '".MINI_ITMS_STOCK."' group by pq.product_id order by p.created_dt") or die(mysql_error());
if(mysql_num_rows($refundquery) > 0)
{
$row1 = array("Main Category","Sub Category","Item Collection","Item Name", "Item Code", "Stock Code", "Barcode", "Description", "Weight", "Colour", "Size", "Wholesale Price", "RRP", "Image1", "Image2", "Image3", "Image4", "Image5", "Quantity", "Quantity Code");
foreach ($row1 as $value1 )
{
$data .= $value1."\t";
}
$data .= "\n";
for($p=0;$p<mysql_num_rows($refundquery);$p++)
{
$orderinfo = mysql_fetch_array($refundquery);
$prod_id = $orderinfo['id'];
$product_name = stripslashes($orderinfo['product_name']);
$product_code = stripslashes($orderinfo['product_code']);
$product_desc = strip_tags(stripslashes($orderinfo['product_desc']));
$item_collection = stripslashes($orderinfo['item_collection']);
$main_category_name = stripslashes($orderinfo['main_category_name']);
$sub_category_name = stripslashes($orderinfo['sub_category_name']);
$weight = stripslashes($orderinfo['weight']);
$was_price = get_table_data("product_price","price","product_id=".$prod_id." AND store_id=".$_REQUEST['store_id'] . " AND currencies_id = $currency");
$was_active = get_table_data("product_website","active","product_id=".$prod_id." AND store_id=".$_REQUEST['store_id'] . "");
$colour_name = 'N/A';
$size_name = 'N/A';
$quantity = $info['quantity'];
$barcode = $info['barcode'];
$psql = mysql_query("SELECT * FROM `product_quantity` where ".$quantity_store_query1." product_id = '$prod_id' and `quantity` >= '".MINI_ITMS_STOCK."'") or die(mysql_error());
$psql2 = mysql_query("SELECT * FROM `product_category` where product_id = $prod_id");
if(mysql_num_rows($psql) > 0)
if($was_active == 1)
{
for($k=0;$k<mysql_num_rows($psql);$k++)
{
$kinfo = mysql_fetch_array($psql);
$kinfo2 = mysql_fetch_array($psql2);
$category_name = get_table_data("category","cat_name","cat_id=".$kinfo2['category_id']);
$colour_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['color_id']);
$size_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['size_id']);
$images = get_image_data($prod_id,$kinfo['color_id']);
$quantity = $kinfo['quantity'];
$barcode = $kinfo['barcode'];
$RRP = ceil($was_price * 2.5);
?>
<?php
if ($quantity > 5) {
$quantity_code = 2;
} elseif ($quantity < 5) {
$quantity_code = 1;
} elseif ($quantity = 0){
$quantity_code = 0;
?>
<?php
$export=array($main_category_name,$sub_category_name,$item_collection,$product_name,$product_code,$product_code.$colour_name.$size_name,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$RRP,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity,$quantity_code);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}
$csv_output .= "\n";
}
}
}
else
{
$p_sql = mysql_query("SELECT * FROM `product` where id = $prod_id and quantity >= ".MINI_ITMS_STOCK." and is_color = 0 and is_size = 0");
if(mysql_num_rows($p_sql) > 0)
if($was_active == 1)
{
$kinfo = mysql_fetch_array($p_sql);
$images = get_image_data($prod_id,0);
$export=array($main_category_name,$sub_category_name,$item_collection,$category_name,$product_name,$product_code,$product_code.$colour_name.$size_name,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$RRP,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity,$quantity_code);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}$csv_output .= "\n";
}
}
}
$data = str_replace("\r","",$data);
$to_date = date("d-m-y-h-i-s");
$excel_name = "BANNED_STOCK_UPDATE";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"".$excel_name.".xls\"");
header("Pragma: no-cache");
header("Expires: 0");
print $data.$csv_output;
exit;
}
}
?>

How to add more elements to specific key in array?

I am trying to convert xml node into array, i have 3 separated nodes inside parent match node, so i need to convert all them into array.
When i try this code
foreach($lineup->away->player as $player){
$awaysquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
and call this matcharr by:
print_r($matcharr);
There is just last element for each index/array, i want to get all players from lineup tag.
So print_r prints this:
Array ( [goal] => 2456166 [name] => Luís Leal [number] => 9 [playerid]
=> 2474225 [yellow] => 2486288 [subin] => 2353344 [subout] => 0 [minute] => NA )
for each match tag, but i need to get 22 players for each match.
Here is more detailed code:
foreach($week->match as $match){
$matcharr = array();
//var_dump($match);
$fixid = 0;
if($match->attributes()->id == 0 || $match->attributes()->id == ''){
if($match->attributes()->alternate_id == 0 || $match->attributes()->id == ''){
$fixid = $match->attributes()->alternate_id_2;
}
else{
$fixid = $match->attributes()->alternate_id;
}
}
else{
$fixid = $match->attributes()->id;
}
$dbdate = date('Y-m-d',strtotime($match->attributes()->date));
$dbtime = date('H:i:s', strtotime($match->attributes()->time));
//if($dbdate == date('Y-m-d')){
echo $dbdate . ' ' . date("Y-m-d");
$datetime = date('Y-m-d H:i:s',strtotime($dbdate . $dbtime));
$fcountry = $this->filterCountries($results->attributes()->country);
$stadium = $match->attributes()->venue;
$city = $match->attributes()->venue_city;
//echo $fcountry;
//$home = $match->home->attributes()->name;
//$away = $match->away->attributes()->name;
$home = '';
$away = '';
$homeid = 0;
$awayid = 0;
$hgoals = 0;
$agoals = 0;
if($match->home){
$home = $this->getMap($fcountry,$match->home->attributes()->name);
$away = $this->getMap($fcountry,$match->away->attributes()->name);
$homeid = $this->filterTeams($fcountry,$match->home->attributes()->id);
$awayid = $this->filterTeams($fcountry,$match->away->attributes()->id);
$hgoals = $match->home->attributes()->score;
$agoals = $match->away->attributes()->score;
}
$eventname = $home . ' - ' . $away;
$halftimehomegoals = 0;
$halftimeawaygoals = 0;
if($match->halftime->attributes()->score != NULL){
$halftime = explode("-",$match->halftime->attributes()->score);
$halftimehomegoals = (int)$halftime[0];
if(array_key_exists(1,$halftime)){
$halftimeawaygoals = (int)$halftime[1];
}
}
$homescore = '';
$awayscore = '';
if($match->goals->goal != NULL){
foreach($match->goals->goal as $goal){
if($goal->attributes()->team == 'home'){
$homescore .= $goal->attributes()->minute.': '.
$goal->attributes()->player.'; ';
$matcharr['goal'] = (int)$goal->attributes()->playerid;
}
elseif($goal->attributes()->team == 'away'){
$awayscore .= $goal->attributes()->player.'; ';
$matcharr['goal'] = (int)$goal->attributes()->playerid;
}
}
}
$homesquad = '';
$awaysquad = '';
if($match->lineups != NULL){
foreach($match->lineups as $lineup){
if($lineup->home->player != NULL){
foreach($lineup->home->player as $player){
$homesquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
}
if($lineup->away->player != NULL){
foreach($lineup->away->player as $player){
$awaysquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
}
}
}
$homesub = '';
$awaysub = '';
if($match->substitutions != NULL){
foreach($match->substitutions as $subs){
if($subs->home->substitution != NULL){
foreach($subs->home->substitution as $sub){
$homesub .= $sub->attributes()->minute."' in: ".
$sub->attributes()->player_in_name . '; ' . ' out: ' .
$sub->attributes()->player_out_name . '; ';
$matcharr['subin'] = (int)$sub->attributes()->player_in_id;
$matcharr['subout'] = (int)$sub->attributes()->player_out_id;
$matcharr['minute'] = (string)$sub->attributes()->minute;
}
}
if($subs->away->substitution != NULL){
foreach($subs->away->substitution as $sub){
$awaysub .= $sub->attributes()->minute."' in: ".
$sub->attributes()->player_in_name . '; ' .
$sub->attributes()->player_out_name . '; ';
$matcharr['subin'] = (int)$sub->attributes()->player_in_id;
$matcharr['subout'] = (int)$sub->attributes()->player_out_id;
$matcharr['minute'] = (string)$sub->attributes()->minute;
}
}
}
}
echo $leaguename . ' ' . $leagueid . ' ' . $fixid . ' ' . $eventname.'<br>';
print_r($matcharr);
Add some counter variable before storing it in array like below
$element_count = 0;//Counter variable
foreach ($lineup->away->player as $player) {
$awaysquad .= $player->attributes()->name . '; ';
$matcharr[$element_count]['name'] = (string)$player->attributes()->name;
$matcharr[$element_count]['number'] = (int)$player->attributes()->number;
$matcharr[$element_count]['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ", $player->attributes()->booking));
if (substr_count($player->attributes()->booking, "YC") == 1) {
$matcharr[$element_count]['yellow'] = (int)$player->attributes()->id;
}
elseif ((substr_count($player->attributes()->booking, "RC") == 1) or ($yellowcount == 3)) {
$matcharr[$element_count]['red'] = (int)$player->attributes()->id;
}
$element_count++;
}

Styling Dynamically created selection drop box using HTML and CSS. How?

This code is in php file. How I will style tag with "Select Size" and customize the drop down section. Below is one div which i want to style but ht class is created dynamically. And here div drop box are created dynamically and the data entered is also been done dynamically. HELP
$i = 0;
$attribArr = array();
$sizeArr = array();
$colorArr = array();
$colorStr = "color";
$sizeStr = "size";
$phpArray = array(
0 => 001 - 1234567,
1 => 1234567,
2 => 12345678,
3 => 12345678,
4 => 12345678
);
foreach ($order['cart_items'] as $item) {
$i++;
$cssNo = $i % 5;
if ($cssNo == 0) {
$cssNo = 5;
}
$giftcss = "gift-info gift" . $cssNo;
// Get products description
$presult = array();
$productId = $item['product_id'];
$reslt = getProductOptions($productId);
$values = $reslt['values'];
info('option type=' . $reslt['type'] . ' Name=' . $reslt['name']);
$sizeOptionValues = '<option>';
$colorOptionValues = '<option>';
if ($reslt['name'] == 'Size') {
foreach ($values as $value) {
info('vl=' . $value['options_value_name']);
$sizeOptionValues.= str_replace(' ', '', $value['options_value_name']) . '</option><option>';
}
}
if ($reslt['name'] == 'Color') {
foreach ($values as $value) {
info('vl=' . $value['options_value_name']);
$colorOptionValues.= $value['options_value_name'] . '</option><option>';
}
}
$pquery = "SELECT products_description, pr.products_image, products_name FROM "
. TABLE_PRODUCTS_DESCRIPTION . " AS pd JOIN " . TABLE_PRODUCTS . " as pr ON pr.products_id = pd.products_id WHERE pd.products_id=" . $productId;
$presult = $db->Execute($pquery);
$product_name = $presult->fields['products_name'];
$product_image = $presult->fields['products_image'];
$product_desc = $presult->fields['products_description'];
$prodImgs = explode(".", $product_image);
$prodImg0 = $prodImgs[0];
$prodImgExt = $prodImgs[1];
$prod_img_name = $prodImg0 . 'v.' . $prodImgExt;
info("getOrder", "Product Name=" . $product_name . " prod image=" . $prod_img_name);
$prod_desc_url = EL_PROD_DESC_PATH . $productId;
$prodAttrQry = "SELECT * FROM " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " WHERE products_prid = " . $productId . " AND orders_id = " . $orderId;
$attrReslt = $db->Execute($prodAttrQry);
$color = false;
$colorValue = '';
$size = false;
$sizeValue = '';
$personalised = false;
$attr = false;
$personalisedMsg = '';
if ($attrReslt->RecordCount() > 0) {
$attr = true;
$attrArr = array();
while (!$attrReslt->EOF) {
$optName = $attrReslt->fields['products_options'];
$optValue = $attrReslt->fields['products_options_values'];
if ($optName == 'Size') {
$size = true;
$sizeValue = $optValue;
} else if ($optName == 'Color') {
$color = true;
$colorValue = $optValue;
} else if ($optName == '') {
$personalised = true;
$rslt = explode(".", $optValue);
if ((isset($rslt[1]) && $rslt[1] == 'jpg') || (isset($rslt[1]) && $rslt[1] == 'png')) {
$personalisedMsg = "<b>Uploaded Image</b> " . "<br><img style = 'width:200px; height:200px;'src = '$optValue'/>";
} else {
$personalisedMsg = '<b>Personal Message</b><br>' . $optValue;
}
}
$sizeArr[$i] = $sizeValue;
$colorArr[$i] = $colorValue;
$attribArr['personalise_val' . $i] = $personalisedMsg;
$attrReslt->MoveNext();
}
}
$colorVisibility = 'none';
$sizeVisibility = 'none';
$personalisedVisib = 'none';
$headlineVisib = 'none';
if ($color) {
$colorVisibility = 'inline';
$headlineVisib = 'inline';
}
if ($size) {
$sizeVisibility = 'inline';
$headlineVisib = 'inline';
}
if ($personalised) {
$personalisedVisib = 'inline';
}
$secondScreen .= <<
<div class="{$giftcss}">
<input type="hidden" name= "product_id{$i}" value="{$productId}"/>
<div class="gift-img"><img src="http://{$domainName}/gifts/images/{$prod_img_name}" height="250"></div>
<div class="divider"></div><div class="gift-desc"><h3>{$product_name}</h3><span>{$product_desc}</span></div>
<div style="width:100%;"><h3 style="display:{$headlineVisib}">Customize your gift</h3><br>
<p style="display:{$sizeVisibility};">Select Size<select id = "prod_size{$i}" name="prod_size{$i}" >{$sizeOptionValues}</select></p>
<p style="display:{$colorVisibility};">Select Color<select id = "prod_color{$i}" name="prod_color{$i}" >{$colorOptionValues}</select></p>
<p style="display:{$personalisedVisib};">{$personalisedMsg}</p></div>
MARKUP;
$secondScreen .= <<<MARKUP
Im not entirely sure what you mean? But if it's what I think you mean. To print out your php values into the class='' attribute you would:
<div class="<?php echo $giftcss; ?>">
<input type="hidden" name= "product_id<?php echo $i; ?>" value="{$productId}"/>
<div class="gift-img">
<img src="http://<?php echo $domainName; ?>/gifts/images/<?php echo $prod_img_name; ?>" height="250"></div>
Simply <?php echo $variable; ?> into each html attribute.

Custom table sorting not working correct

I am creating a data table that has sortable links but when I click on the link say "username" if i click on that multiple times it makes the url have lots of asc example: http://localhost/riwakawebsitedesigns-website/admin/users/status/ascascascascascascasc it should just be
Sorting Asc http://localhost/riwakawebsitedesigns-website/admin/users/status/asc
And then if click again and so on.
Sorting Desc http://localhost/riwakawebsitedesigns-website/admin/users/status/desc
This here is how pagination looks in url http://localhost/riwakawebsitedesigns-website/admin/users/1
I cannot figure out why each time i click on table head link that it creates so many asc etc. How can I fix it.
What's wrong with sort code. The pagination works fine. Please note I have use codeigniter pagination but not to my liking.
<?php
class Users extends MX_Controller {
public function index() {
$this->getList();
}
public function getList() {
$this->load->library('paginations');
$sort_segment = $this->uri->segment(3);
if (isset($sort_segment)) {
$sort = $sort_segment;
} else {
$sort = 'username';
}
$order_segment = $this->uri->segment(3);
if (isset($order_segment)) {
$order = $order_segment;
} else {
$order = 'asc';
}
$page_segment = $this->uri->segment(4);
if (isset($page_segment)) {
$page = $page_segment;
} else {
$page = 1;
}
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['title'] = "Users";
$this->load->model('admin/user/model_user');
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'date_added' => $result['date_added'],
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'])
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = "1";
$paginations->url = site_url('admin/users' .'/'. $url .'/'. '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}
Thanks so much to #AdrienXL which gave me the idea what problem was.
I now have fixed it. I had doubled up on my page and sort and orders $_GET. So there for i have now just used uri segments and removed the doubled up code and change a couple of things in model
For people who do not want to use codeigniter pagination class.
You can use my example:
My Users:
<?php
class Users extends MX_Controller {
public function index() {
$this->load->library('paginations');
$this->load->model('admin/user/model_user');
// Sort
if (null !==($this->uri->segment(3))) {
$sort = $this->uri->segment(3);
} else {
$sort = 'username';
}
// Order
if (null !==($this->uri->segment(4))) {
$order = $this->uri->segment(4);
} else {
$order = 'asc';
}
// Page
if (null !==($this->uri->segment(3))) {
$page = $this->uri->segment(3);
} else {
$page = 1;
}
$url = '';
// Sort
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
// Order
if (null !==($this->uri->segment(4))) {
$url .= $this->uri->segment(4);
}
// Page Number
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'status' => ($result['status'] ? "Enabled" : "Disabled"),
'date_added' => date(strtotime($result['date_added'])),
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'] . $url)
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = $admin_limit;
$paginations->url = site_url('admin/users' .'/'. $url . '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My View
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?php if ($sort == 'username') { ?>
Username
<?php } else { ?>
Username
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'status') { ?>
Status
<?php } else { ?>
Status
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'date_added') { ?>
Date Added
<?php } else { ?>
Date Added
<?php } ?></td>
<td class="text-right">Action</td>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) { ?>
<tr>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['status'];?></td>
<td><?php echo $user['date_added'];?></td>
<td><a href="<?php echo $user['edit'];?>">Edit</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="row">
<div class="col-sm-6 text-left"><?php echo $pagination; ?></div>
<div class="col-sm-6 text-right"><?php echo $results; ?></div>
</div>
</div>
Model Function
public function getUsers($data = array()) {
$sql = "SELECT * FROM `" . $this->db->dbprefix . "user`";
$sort_data = array(
'username',
'status',
'date_added'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY username";
}
if (isset($data['order']) && ($data['order'] == 'desc')) {
$sql .= " desc";
} else {
$sql .= " asc";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->result_array();
}
Routes:
$route['admin/users'] = "admin/user/users/index";
$route['admin/users/edit/(:any)'] = "admin/user/users/edit/$1";
$route['admin/users/(:any)'] = "admin/user/users/index/$1";
$route['admin/users/(:any)/(:any)/(:any)'] = "admin/user/users/index/$1/$2/$3";
Custom Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}

Pagination not taking value to second page?

$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '')
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
echo "";
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
Pagination is working correctly for select $today. Here pagination is not taking value to second page in the case of select $mydate. If second page of $mydate clicks, again going to $today. ie Second click is not posting $mydate to next page. How can I take the value to second page?
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
function pagination in your code is not returning the resulting mysql query resource, and your code is not receiving that from the pagination function call
you need
to add return $pg_result; in your pagination function
and add $result=pagination(....
Edit:
Sorry, I noticed you added pg_result to global, which does not need return and the solution I said, but you don't need mysql_query and fetch before that and I don't see where you print the results. there is only echo "", you can try the one I edited last, and see if it works for you.
Edit:
$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
//$result=mysql_query($sql);
$pg_result=pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '' && is_resource($pg_result))
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
var_dump($data);
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
return $pg_result;
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
Looks like you're mixing up the concept of $_POST and $_GET.
By having your pagination links point to '<a href="'.$pg_page_name.'?page_id='.$i . $pg_user_param.'"... You should be intercepting $_GET['page_id'] before you make your SQL query.
Your top code references $_POST['datepicker'] but you don't mention a form anywhere and your pagination links certainly aren't posting that data in your example.
You should use $pg_param = ""; to pass your own query parameters. Ex: &date=$date_value:
$pg_param = "&date=$date_value";

Categories