I've adapted a simple paginated gallery to my needs, but it doesn't work as expected: usually it puts well the first "page" og pictures then in some cases it just skip some pictures and then go to further ones, in other cases it just do not load any other page (I'm using infinitescroll)
here is the php function:
function makeGallery($path, $directory, $seo){
$dir = $path . "/" . $directory;
$handle = opendir($dir);
while ($file = readdir($handle)){
if($file == '.' OR $file == '..' or $file == 'thumbs' or $file == '.DS_Store')
continue;
else
$result_array[]=$file;
}
$filecount = count(glob("" . $dir . "*.jpg"));
closedir($handle);
array_multisort($result_array, SORT_ASC);
$rows = 3;
$cols = 8;
if(isset($_GET['page'])){
$page = $_GET['page'];
}else{
$page = 0;
}
$num_pics = count($result_array);
$cells = $rows * $cols;
$pages = ceil($num_pics / $cells);
$num_pages = $pages - 1;
$output = array();
$slices = array();
$push = 0;
$showpage = $page + 1;
for($k=0;$k<$pages;$k++){
array_push($slices, $push);
$push = $push + $cells;
}
for($k=0;$k<$pages;$k++){
if($page == key($slices)){
$output = array_slice($result_array, current($slices), $cells);
}
next($slices);
}
reset($output);
print '<div class="container-fluid">
<div class="row">';
print "<ul id='photoswipe' class='thumbnails'>";
for($i=0;$i<$rows;$i++){
for($j=0;$j<$cols;$j++){
if(current($output) != false){
$value = current($output);
$parts = Explode('.', $value);
$title = $parts[count($parts) - 2];
$parts = Explode('-', $title);
$title = $parts[1];
if ($title == "") $title = $value;
print "<li class='box'><a title='$title' rel='group' class='thumbnails' href='$dir/$value'><img width='$width' height='inherrit' src='$dir/thumbs/$seo-$value' /></a></li>";
next($output);
}else{
print "</ul>";
}
}
}
$ref = $_SERVER['PHP_SELF'];
if($num_pages == '0'){
print " ";
print " ";
}elseif(($page == '0')||($page == '')){
$next = $page + 1;
print " ";
print "<a id='next' href='$ref?page=$next'> </a>";
}elseif($page == $num_pages){
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print " ";
}else{
$next = $page + 1;
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print "<a id='next' href='$ref?page=$next'> </a>";
}
echo "<nav id='page-nav'>
<a href='$ref?page=$next'></a>
</nav></div></div>";
}
I'm sure there should be some silly bug that i've not spotted and i hope that some experienced php programmer can find it very easily.
you could see the gallery (and its problem) on http://eikonabox.com/page/portrait.php
(in the portrait gallery as you can see it jumps from the number 24 directly to number 49)
Thank you all
If somone get stuck in this kind of problem I've resolved this way:
function makeGallery($path, $directory, $seo){
$dir = $path . "/" . $directory;
$filearray = array();
if ($fil = opendir($dir)) {
while (($file = readdir($fil)) !== false) {
if ($file != "." && $file != ".." && $file != "thumbs" && $file != ".DS_Store") {
$filearray[] = $file;
$page = empty($_GET['page']) ? 1 : $_GET['page'];
$num_per_page = 25;
$total_pages = ceil(count($filearray)/$num_per_page);
}
}
array_multisort($filearray, SORT_ASC);
print '<div class="container-fluid">
<div class="row">';
print "<ul id='photoswipe' class='thumbnails'>";
for($i = ($page - 1) * $num_per_page; $i < $page * $num_per_page; $i++){
$value = basename($filearray[$i]);
$parts = Explode('.', $value);
$title = $parts[count($parts) - 2];
$parts = Explode('-', $title);
$title = $parts[1];
if ($title == "") $title = $value;
if($value != "")
print "<li class='box'><a title='$title' rel='group' class='thumbnails' href='$dir/$value'><img width='$width' height='inherrit' src='$dir/thumbs/$seo-$value' /></a></li>";
}
closedir($fil);
}
print "</ul>";
$ref = $_SERVER['PHP_SELF'];
if($num_pages == '0'){
print " ";
print " ";
}elseif(($page == '0')||($page == '')){
$next = $page + 1;
print " ";
print "<a id='next' href='$ref?page=$next'> </a>";
}elseif($page == $num_pages){
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print " ";
}else{
$next = $page + 1;
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print "<a id='next' href='$ref?page=$next'> </a>";
}
echo "<nav id='page-nav'>
<a href='$ref?page=$next'></a>
</nav></div></div>";
}
Related
I need a little bit of help.
I have an XML file as a database. From it, I need to create a pagination with 25 elements per page with Next and Previous buttons, but with my skills I'm stuck at it.
At the moment, I've written this code, but every page it reset the ID from the database to 0, so it doesn't work.
<?php
$xml = simplexml_load_file("SITE_URL/database_gamecard.xml");
$ids = array();
$count = 0;
foreach($xml->gamecard as $id) {
$ids[] = $id;
}
//Order IDs by url names
//usort ($ids, function($a, $b) {
//$url = $id->url;
//return strcmp($a[$url], $b[$url]);
//});
function PopulatePage($id) {
$url = $id->url;
$img = $id->img;
echo '<a class="darken" href="' . $url . '"><img width="320" height="240" src="' . $img . '"></a>';
}
function StopCount() {
$page = intval($_GET['page']);
$pageurl = "SITE_URL/list.php?page=";
$count = 0;
$page = $page + 1;
$newurl = $pageurl . $page;
echo "<a href='" . $newurl . "'>Next</a>";
}
//Test generating pages
foreach ($ids as $id) {
$count++;
if($page == 1) {
PopulatePage($id);
if($count == 25) {
StopCount();
break;
}
}
if($page == 2) {
PopulatePage($id);
if($count == 25) {
StopCount();
break;
}
}
}
?>
I am getting this error:
Notice: Undefined index: REDIRECT_URL in /home/webccans/public_html/index.php
I have Tried taking out the redirect and it still works. I need help try to define the index "REDIRECT_URL" I would appreciate and pointers or advice.
The page is display, and the site works fine but this error is on the home page
This is the Code on my index page
<?
include('application.php');
$header = false;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (($request = trim($_SERVER['REDIRECT_URL'])) == '') {
// Deal with direct requests
$Page = (isset($_GET['Page'])) ? $_GET['Page'] : 1;
$Page = $CMS->getPageContent($Page);
} else {
// Deal with "friendly" URL 404 pages
$pages = explode('/', $request);
array_shift($pages);
$page = array_pop($pages);
if (($pos = strpos($page, '.')) === false) {
$ext = '';
} else {
$ext = substr($page, strpos($page, '.'));
if ($pos = strpos($ext, '?')) $ext = substr($ext, 0, $pos);
}
if ($page == '') {
// have a CMS page or the home page
} else if ($ext == '.htm' || $ext == '.html' || $ext == '.php') {
$PageURL = substr($page, 0, strlen($ext) * -1);
if ($PageURL != "index") {
// Possible have a CMS page
array_push($pages, $PageURL);
}
} else if ($ext == '') {
// have a CMS page
array_push($pages, $page);
} else {
$CMS->show404Page();
$header = true;
}
if (($numPages = count($pages)) > 0) {
// Get PageID
$select = 'SELECT ';
$from = ' FROM site_content AS page0 LEFT JOIN site_content AS
page ON (page0.ParentID = page.PageID) ';
$where = ' WHERE (page0.ParentID = 0 OR page.Display = 0) ';
for ($idx = 0; $idx < $numPages; ++$idx) {
$where .= ' AND ';
if ($idx > 0) {
$select .= ', ';
$from .= ' JOIN site_content AS page' . $idx . ' ON (page'
. ($idx - 1) . '.PageID = page' . $idx . '.ParentID)';
}
$select .= 'page' . $idx . '.PageID ';
$where .= 'page' . $idx . '.PageURL = "' . $DB-
>escape(strtolower($pages[$idx])) . '"';
#$select1 = 'page' . $idx . '.PageID ';
}
$qid = $DB->query($select . $from . $where);
if ($row = $DB->fetchRow($qid)) {
$PageID = $row[$numPages - 1];
$OpenedPages = $row;
#print_r ($row);
}
else {
$CMS->show404Page();
$header = true;
}
} else {
$PageID = 1;
}
$Page = $CMS->getPageContent($PageID);
#echo '<script language="javascript">' . 'alert("' . $PageID . '")'
.
'</script>';
#echo '<script language="javascript">' . 'alert("' . $ParentId . '")'
. '</script>';
}
$TopPage = $CMS->getTopParent($Page->PageID);
if (!$header) header('HTTP/1.1 200 OK');
?>
am using following function to display pagination
public function paginationLinks(){
$outputString = "";
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$newsNumber = $res[0];
$q->closeCursor();
for($i = 1; $i <= ceil($newsNumber / $this->newsByPage); $i++){
$outputString .="<li><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
return $outputString;
}
and this is how i display
<ul class="pagination pagination-sm">
<?php echo $news->paginationLinks(); ?>
</ul>
now bootstrap doesn't display active page its because of function
how do i add some more option like next, previous and :active
just replace your function with this one
public function paginationLinks(){
$outputString = "";
$crpage = isset($_GET['page']) && trim($_GET['page']) != ''?trim($_GET['page']):1;
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$newsNumber = $res[0];
$q->closeCursor();
for($i = 1; $i <= ceil($newsNumber / $this->newsByPage); $i++){
if($crpage == $i){
$outputString .="<li class='active'><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}else{
$outputString .="<li><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
}
return $outputString;
}
For next or previous see that link
great example for PHP pagination.
Please try this .I hope this help you
public function paginationLinks(){
$num_rec_per_page = 10;
$outputString = "";
$page = (isset($_GET['page']) && $_GET['page'] != '') ? trim($_GET['page']) : 1;
$start_from = ($page-1) * $num_rec_per_page;
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$total_records = $res[0];
$q->closeCursor();
$total_pages = ceil($total_records / $num_rec_per_page);
$outputString .= "<li><a href='?page=1'>".'|<'."</a></li>"; // Goto 1st page
if($page > 1){
$prev = $page - 1;
$outputString .= "<li><a href='?page=".$prev."'>Prev</a></li>"; // Goto previous page
}
for ($i=1; $i<=$total_pages; $i++) {
$activeClass = ($page == $i) ? 'active' : '';
$outputString .="<li class=".$activeClass."><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
if($page < $total_pages){
$next = $page + 1;
$outputString .= "<li><a href='?page=".$next."'>Next</a></li>"; // Goto Next page
}
if($page > 1){
$outputString .= "<li><a href='?page=".$total_pages."'>".'|>'."</a></li>"; // Goto last page
}
return $outputString;
}
I have the following script to display files inside a directory
<?PHP
# The current directory
$directory = dir("./");
# If you want to turn on Extension Filter, then uncomment this:
$allowed_ext = array(".deb", ".ext", ".ext", ".ext", ".ext", ".ext");
$do_link = TRUE;
$sort_what = 0; //0- by name; 1 - by size; 2 - by date
$sort_how = 0; //0 - ASCENDING; 1 - DESCENDING
# # #
function dir_list($dir){
$i=0;
$dl = array();
if ($hd = opendir($dir)) {
while ($sz = readdir($hd)) {
if (preg_match("/^\./",$sz)==0) $dl[] = $sz;$i.=1;
}
closedir($hd);
}
asort($dl);
return $dl;
}
if ($sort_how == 0) {
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return -1;
else return 1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return -1;
else return 1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return -1;
else return 1;
}
}else{
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return 1;
else return -1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return 1;
else return -1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return 1;
else return -1;
}
}
##################################################
# Getting The information
##################################################
$i = 0;
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
# Sorting the information
#################################################
switch ($sort_what) {
case 0:
usort($new_array, "compare0");
break;
case 1:
usort($new_array, "compare1");
break;
case 2:
usort($new_array, "compare2");
break;
}
###############################################################
# Displaying the information
###############################################################
$i2 = count($new_array);
$i = 0;
echo "<table class='CSSTableGenerator'>
<tr>
<td width=290>File name (Download)</td>
<td align=center width=70>Downloads</td>
<td align=center width=70>Depiction</td>
<td align=center width=50>Size</td>
<td align=center width=85>Modified</td>
</tr>";
for ($i=0;$i<$i2;$i++) {
if (!$do_link) {
$line = "<tr><td>" . $new_array[$i][0];
$line .= '</td><td>Depiction</td>';
$line .= "<td>" . number_format(($new_array[$i][1]/1024)) . " KB</td>";
$line .= "<td>" . $new_array[$i][3] . "</td></tr>";
}else{
$line = '<tr><td align=left ><A class="ex1" HREF="' .
$new_array[$i][0] . '">' .
$new_array[$i][0] .
"</A></td>";
$line .= '<td> </td>';
$line .= '<td>Depiction</td>';
$line .= "<td>" . number_format(($new_array[$i][1]/1024)) . " KB</td>";
$line .= "<td>" . $new_array[$i][3] . "</td></tr>";
}
echo $line;
}
echo "</table>";
?>
The output looks like that:
I am trying to fill the downloads column by getting the download counts of each file from mysql table
So i am facing 2 issues here:
How to get the stats using the array of the files $new_array[$i][0]
How can i then add this mysql query output inside $line .= '<td> </td>';
I have tried getting the stats from the table using this:
include("../config.php");
$query = "SELECT stats FROM download WHERE filename='$new_array[$i][0]'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$line .= '<td>' . $row['stats'] . '</td>';
}
but it didn't work, i think the issue is with the array $new_array[$i][0] because i tried writing a filename filename='com.name.app3_2.2-1_iphoneos-arm.deb' and i got the stats of this file
In your "getting the information part", you must initialise your arrays thusly:
##################################################
# Getting The information
##################################################
$i = 0;
$new_array = array();
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$new_array[$i] = array();
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
In addition, I have noted that your line:
$query = "SELECT stats FROM download WHERE filename='$new_array[$i][0]'";
Would cause $query to be equal to:
SELECT stats FROM download WHERE filename='Array[0]'
When $i is 0.
What you should do is use the mysqli library thusly:
$mysqli = new mysqli("example.com", "user", "password", "database");
$query = "SELECT stats FROM download WHERE filename=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $new_array[$i][0]);
$stmt->execute();
$stmt->bind_result($stats);//stats turns into a reference by default.
while($stmt->fetch()) { //$stats now contains the stats
$line .= '<td>'. htmlentities($stats).'</td>';
}
To deal with the problem of missing cells you just described, you might try:
$mysqli = new mysqli("example.com", "user", "password", "database");
$query = "SELECT stats FROM download WHERE filename=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $new_array[$i][0]);
$stmt->execute();
$stmt->bind_result($stats);//stats turns into a reference by default.
$fetched = false;
while($stmt->fetch()) { //$stats now contains the stats
$line .= '<td>'. htmlentities($stats).'</td>';
$fetched = true;
}
if(!$fetched) {
$line .= '<td></td>'
}
I have a list of directory name and need to get the first letter from each name and just display it once before the start of that lettered group ie;
what I have:
1
2
3
4
5
Aberdeen
Arundel
Aberyswith
Bath
Bristol
Brighton
Cardiff
coventry
what I would like:
#
1
2
3
4
5
A
Aberdeen
Arundel
Aberyswith
B
Bath
Bristol
Brighton
C
Cardiff
coventry
function htmlDirList($subdirs) {
global $z_self, $z_img_play, $z_img_lofi, $z_img_more, $z_admin,
$z_img_down, $z_img_new, $zc;
$now = time();
$diff = $zc['new_time']*60*60*24;
$num = 0;
$dir_list_len = $zc['dir_list_len'];
if ($zc['low']) { $dir_list_len -= 2; }
$html = "";
$checkbox = ($z_admin || ($zc['playlists'] && $zc['session_pls']));
/**/
$row = 0;
$items = sizeof($subdirs);
$cat_cols = "2";
$rows_in_col = ceil($items/$cat_cols);
if ($rows_in_col < $cat_cols) { $cat_cols = ceil($items/$rows_in_col); }
$col_width = round(100 / $cat_cols);
$html = "<table width='600'><tr>";
$i = 0;
/**/
foreach ($subdirs as $subdir => $opts) {
if ($row == 0) {
$class = ($cat_cols != ++$i) ? ' class="z_artistcols"' : '';
$html .= "<td $class valign='top' nowrap='nowrap' width='$col_width%'>";
}
/*$currentleter = substr($opts, 0 , 1);
if($lastletter != $currentleter){
echo $currentleter;
$lastletter = $currentleter;
}*/
if($alphabet != substr($opts,0,1)) {
echo strtoupper(substr($opts,0,1)); // add your html formatting too.
$alphabet = substr($opts,0,1);
}
$dir_len = $dir_list_len;
$dir = false;
$image = $opts['image'];
$new_beg = $new_end = "";
if (substr($subdir, -1) == "/") {
$dir = true;
$subdir = substr($subdir, 0, -1);
}
$path_raw = getURLencodedPath($subdir);
$href = "<a href='$path_raw";
if (!$dir) {
if ($zc['download'] && $zc['cmp_sel']) { $html .= "$href/.lp&l=8&m=9&c=0'>$z_img_down</a> "; }
if ($zc['play']) { $html .= "$href&l=8&m=0'>$z_img_play</a> "; }
if ($zc['low'] && ($zc['resample'] || $opts['lofi'])) { $html .= "$href&l=8&m=0&lf=true'>$z_img_lofi</a> "; }
if ($checkbox) { $html .= "<input type='checkbox' name='mp3s[]' value='$path_raw/.lp'/> "; }
$num++;
if ($zc['new_highlight'] && isset($opts['mtime']) && ($now - $opts['mtime'] < $diff)) {
$dir_len -= 5;
if ($z_img_new) {
$new_end = $z_img_new;
} else {
$new_beg = $zc['new_beg'];
$new_end = $zc['new_end'];
}
}
}
$title = formatTitle(basename($subdir));
if (strlen($title) > $dir_len) {
$ht = " title=\"$title.\"";
$title = substr($title,0,$dir_len).$opts['mtime']."...";
} else {
$ht = "";
}
if ($zc['dir_list_year']) {
$di = getDirInfo($subdir);
if (!empty($di['year'])) $title .= " (".$di['year'].")";
}
$html .= "$href'$ht>$new_beg$title$new_end</a><br />";
$row = ++$row % $rows_in_col;
if ($row == 0) { $html .= "</td>"; }
}
if ($row != 0) $html .= "</td>";
$html .= "</tr></table>";
$arr['num'] = $num;
$arr['list'] = $html;
return $arr;
}
I need help to get work.
The following will display the list of directories, beginning each group with a first letter as beginning of the group (see codepad for proof):
(this assumes $dirs is array containing the names)
$cur_let = null;
foreach ($dirs as $dir) {
if ($cur_let !== strtoupper(substr($dir,0,1))){
$cur_let = strtoupper(substr($dir,0,1));
echo $cur_let."\n";
}
echo $dir . "\n";
}
You just need to add some formatting on your own, suited to your needs.
Edit:
Version grouping under # sign entries that begin with a number, can look like that:
$cur_let = null;
foreach ($dirs as $dir) {
$first_let = (is_numeric(strtoupper(substr($dir,0,1))) ? '#' : strtoupper(substr($dir,0,1)));
if ($cur_let !== $first_let){
$cur_let = $first_let;
echo $cur_let."\n";
}
echo $dir . "\n";
}
Please see codepad as a proof.
Is this what you are looking for?
<?php
$places = array(
'Aberdeen',
'Arundel',
'Aberyswith',
'Bath',
'Bristol',
'Brighton',
'Cardiff',
'coventry'
);
$first_letter = $places[0][0];
foreach($places as $p)
{
if(strtolower($p[0])!=$first_letter)
{
echo "<b>" . strtoupper($p[0]) . "</b><br/>";
$first_letter = strtolower($p[0]);
}
echo $p . "<br/>";
}
?>
Prints:
A
Aberdeen
Arundel
Aberyswith
B
Bath
Bristol
Brighton
C
Cardiff
coventry
My approach would be to generate a second array that associates the first letter to the array of names that begin with that letter.
$dirs; // assumed this contains your array of names
$groupedDirs = array();
foreach ($dirs as $dir) {
$firstLetter = strtoupper($dir[0]);
$groupedDirs[$firstLetter][] = $dir;
}
Then, you can iterate on $groupedDirs to print out the list.
<?php foreach ($groupedDirs as $group => $dirs): ?>
<?php echo $group; ?>
<?php foreach ($dirs as $dir): ?>
<?php echo $dir; ?>
<?php endforeach; ?>
<?php endforeach; ?>
This allows for a clean separation between two separate tasks: figuring out what the groups are and, secondly, displaying the grouped list. By keeping these tasks separate, not only is the code for each one clearer, but you can reuse either part for different circumstances.
Use something like this, change it to output the HTML the way you want thouugh:
sort($subdirs);
$count = count($subdirs);
$lastLetter = '';
foreach($subdirs as $subdir => $opts){
if(substr($subdir,0,1) !== $lastLetter){
$lastLetter = substr($subdir,0,1);
echo '<br /><div style="font-weight: bold;">'.strtoupper($lastLetter).'</div>';
}
echo '<div>'.$subdir.'</div>';
}
EDIT
Just realized $subdir is associative, made the change above: