How to show only specific amount of result when paginate by PHP - javascript

I have used a php Function from one YouTube tutorial and it's purpose was to get the data from database and paginate it into several pages according to some variables.
The tutorial link:
PHP Pagination Tutorial
The code is working wonderfully and its working in different pages of the current project i'm working on, but when I tried to use the function in search page it is not working as expected, it's showing all of the data [i.e. 100 Rows] in the same page, then it's displaying the pages numbers and when I click on the second page it shows the same result as the first page [100 Rows] and those 100 Rows are all of the data in my data base.
What I'm trying to achieve is to display 10 Results [10 Rows] in each page, and I then get 10 numbers of pages like [1 - 2 - ...until - 10].
I've been using POST request in search page, but I guess that caused the problem, then I tried to use GET request and it is showing like I just explained.
The Code I have for the pagination function is like
<?php
// Function to Paginate the records from any table.
function paginator($dataSelection, $table, $where1, $where2, $order, $pageTo, $inPage) {
global $con, $stmt, $paginationCtrls, $lastPage;
// Getting the rows number of the table
$stmt = $con->prepare("SELECT * FROM $table $where1");
$stmt->execute();
// Assigning rows number of the specified table
$rowCount = count($stmt->fetchAll());
// Get the page number and make sure its an interger
$p = $_GET['page'];
$page = isset($p) ? preg_replace('#[^0-9]#', '', $p) : 1;
// Per Page records
$perPage = $inPage;
// Last Page Number
$lastPage = ceil($rowCount / $perPage);
/*
Checking if the page number is less than 1 then make it one, and if the page number is greater than the last page number, then make it equal to the last page number.
*/
if($page < 1) {
$page = 1;
} elseif($page > $lastPage) {
$page = $lastPage;
}
// This sets the range of rows to $stmt for the chosen $page.
$limit = 'LIMIT ' . ($page - 1) * $perPage . ',' . $perPage;
// This is your $stmt again, it is for grabbing just one page worth of rows by applying $limit to it.
$stmt = $con->prepare("SELECT $dataSelection FROM $table $where2 ORDER BY $order $limit");
// Establish the $paginationCtrls variable.
$paginationCtrls = '';
// Show the pagination if the rows numbers is worth displaying
if($lastPage != 1) {
/*
First we check if we are on page one. If yes then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous pages.
*/
if ($page > 1) {
$previous = $page - 1;
// Concatenate the link to the variable
$paginationCtrls .= '
<li>
<a href="'.$pageTo.'page='.$previous.'" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>';
// Render clickable number links that should appear on the left of the target (current) page number
for($i = $page - 4; $i < $page; $i++) {
if($i > 0) {
// Concatenate the link to the variable
$paginationCtrls .= '
<li>
<a href="'.$pageTo.'page='.$i.'">
'.$i.'
</a>
</li>';
}
}
}
// Render the target (current) page number, but without it being a clickable link
// Concatenate the link to the variable
$paginationCtrls .= '
<li class="active">
<a>
'.$page.'
</a>
</li>';
// Render clickable number links that should appear on the right of the target (current) page number
for($i = $page + 1; $i <= $lastPage; $i++) {
// Concatenate the link to the variable
$paginationCtrls .= '
<li>
<a href="'.$pageTo.'page='.$i.'">
'.$i.'
</a>
</li>';
// if the loop runs for tims then break (stop) it.
if($i >= $page + 4) {
break;
}
}
// This does the same as above, only checking if we are on the last page, if not then generating the "Next"
if ($page != $lastPage) {
$next = $page + 1;
// Concatenate the link to the variable
$paginationCtrls .= '
<li>
<a href="'.$pageTo.'page='.$next.'" aria-label="Next">
<span aria-hidden="true">
»
</span>
</a>
</li>';
}
}
}
and the code I have in search page is as following, and I run the function like so:
<?php
// GET variable
$sQuery = $_GET['searchFor'];
// Force the user to be in the first page if the get page is not set or is empty
if(!isset($_GET['page'])) {
header('location: search?searchFor='.$sQuery.'&page=1');
}
// Require The Paginator Function
require_once $functionsDir . 'public/saj_paginator.php';
// Initialize The Paginator Function
// array('%'.$sQuery.'%')
paginator(
'*',
'saj_articles',
'WHERE art_status = 2',
'WHERE art_title LIKE ? AND art_status = 2',
'art_id DESC',
'search?searchFor='.$sQuery.'&',
10
); //'search?searchFor='.$sQuery.'&',
// LIMIT is not working
// Force the user to not pass the last page
if($_GET['page'] > $lastPage) {
header('location: search?searchFor='.$sQuery.'&page='.$lastPage);
} elseif($_GET['page'] < 1) {
header('location: search?searchFor='.$sQuery.'&page=1');
}
// Connect and retrieve data from database
$stmt = $con->prepare('SELECT * FROM saj_articles WHERE art_title LIKE ? AND art_status = 2');
$stmt->execute(array('%'.$sQuery.'%'));
$count = $stmt->rowCount();
$rows = $stmt->fetchAll();
// if Nothing was found
if(empty($rows)) {
alert('<h3>No Results Found!, Try Something else</h3>', 'info', '', false);
require_once $layoutsDir . 'search/search-form.php';
} else { echo '
<span class="results-count">
'.$count.' Articles Was Found
</span>
';
foreach ($rows as $row): ?>
<div class="panel panel-default">
<div class="panel-heading">
<a href="articles?id=<?php echo $row['art_id'] ?>">
<?php chkTxtDir($row['art_title']) ?>
</a>
</div>
<div class="panel-body">
<span class="label label-primary">Abstract</span>
<br><br>
<p>
<?php
require_once $functionsDir . 'articles/excerpt.php';
excerpt(
$row['art_abstract'],
'articles?id=' . $row['art_id'],
'Continue Reading',
'300');
?>
</p>
</div>
</div>
<?php endforeach;
echo
'<nav aria-label="Page navigation" class="text-center">
<ul class="pagination">
'.$paginationCtrls.'
</ul>
</nav>';
}
And this is the form that I have in the search page
<form action="search" method="GET" class="mb">
<!-- Search Input -->
<div class="form-group">
<input type="search" class="form-control custIn" name="searchFor"
placeholder="Search for Articles..." dir="auto"
<?php
echo isset($_GET['searchFor']) && !empty($_GET['searchFor']) ?
'value="' . htmlentities($_GET['searchFor']) . '"' : ''
?>
required>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit">
Search
</button>
</div>
</form>
Is there any way I can solve this problem?
I have already implemented the pagination in some other pages of the website i'm working in, but only this search page is not working fine.
I admit it, I struggled a lot to understand the concept of the pagination, although I don't understand it completely, but I have very good Idea after working on this website..
If my explanation of this problem isn't that obvious, please let me know which part I have to give you more information about, and If this problem can't just get fixed by PHP, please teach me the best way to do it by JavaScript or jQuery, it is really important to do it..
Thank you.

Related

PHP session from HTML/Javascript onclick not containing the correct value

I have a PHP pagination menu. Each item form the pagination menu contains an a item.
Pagination script:
if ($page_count >= 1 && $page <= $page_count) {
?><li class="page-item <? if($page == 1){echo "active";} ?>"><? echo '<a onclick="myScript(1)" class="page-link">1</a></li>';
$i = max(2, $page - 2);
if ($i > 2)
{
echo ' ... ';
}
for (; $i < min($page + 2, $page_count); $i++) {
?><li class="page-item <? if($i == $page){echo "active";} ?>"><? echo '<a onclick="myScript('. $i .')" class="page-link">' . $i . '</a></li>';
}
if ($i != $page_count)
{
echo ' ... ';
}
?><li class="page-item <? if($page_count == $page){echo "active";} ?>"><? echo '<a onclick="myScript('. $page_count .')" class="page-link">' . $page_count . '</a></li>';
}
When a user clicks on a list <a> item, I want to get the value of the selected item and create a PHP session, containing this item.
This is the Javascript that should create the session:
function myScript(clicked_id)
{
<? $_SESSION["page"] = "clicked_id"; ?>
alert(<? echo "$_SESSION[page]"; ?>);
}
This is working, and in the Javascript alert I get the correct value of the selected item, for example " 2 " if I clicked the list item where the $i value is "2".
The page should refresh, and then, when I check the page session value, I would expect the value " 2 ". However, this is not the case. The value is actually "clicked_id".
This is the code where I check the session:
$page = 1;
if(!empty($_SESSION["page"])) {
$page = $_SESSION["page"];
if($page == 'clicked_id')
{
$page = 1;
}
}
My question is: why is the session not containing the correct value? In the alert the value is correct, but in my check the session doesn't contain the correct value any more. Any help is very much appreciated!
PHP and JS are not compatible; you may not simply include a PHP function in JS.
PHP gets evaluated server-side and javascript gets evaluated client side.
What you probably want to do is to replace your navigations items by links to redirect the user to the desired page.
To understand how PHP works and the result generated by the server, right click on your page and then "View the source code of the page".

how to make an Infinite Page Scroll Effect in Static page using pure javascript

I have searched the web and mostly using jquery and some library to do so. I wonder how we can do it using pure javascript to make an Infinite Page Scroll Effect like twitter does without having to include any library(here i put the search php and html code for reference, and i wanna realize the effects in the search results. I use laravel as a backend). And i am just starting to learn javascript , please treat me as a 10 year old boy. Thanks
//HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Risky Jobs - Search</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="searchWrapper">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method='get' >
<input type="search" name="search">
</form>
</div>
<h3>Risky Jobs - Search Results</h3>
</body>
</html>
// PHP
function build_query($user_search, $sort){
$search_query = "SELECT * FROM posts";
$clean_search = str_replace(',',' ',$user_search);
$search_words = explode(' ', $clean_search);
//to become a array
$final_search_words = array();
if(count($search_words) > 0){
foreach($search_words as word){
if(!empty($word)){// there are circustances that the user input two or more blank so it will result to a blank result
$final_search_words[] = $word;
}
}
}
// Generate a WHERE clause using all of the search keywords
$where_list = array();
if(count($final_search_words) > 0){
foreach($final_search_words as $word){
$where_list[] = "content Like '%$word%'";
}
}
$where_clause = implode(' OR ', $where_list);
//Add the keyword WHERE clause to the search query
if(!empty($where_clause)){
$search_query .= " WHERE $where_clause";
}
// Sort the search query using the sort setting
switch ($sort) {
// Ascending by title
case 1:
$search_query .= " ORDER BY title";
break;
// Desending by title
case 2:
$search_query .= " ORDER BY title DESC";
break;
// Ascending by created_at
case 3:
$search_query .= " ORDER BY created_at";
break;
// Descending by created_at
case 4:
$search_query .= " ORDER BY created_at DESC";
break;
default:
// No sort setting provided, so don't sort the query
//break;
}
return $search_query;
} //END OF build_query() FUNCTION
// This function builds heading links based on the specified sort setting
function generate_sort_links($user_search, $sort){
$sort_links = '';
switch ($sort) {
case 1:
$sort_links .= '<li>Title</td><td>Description</li>';
$sort_links .= '<li>created_Time</td><td>Description</li>';
break;
case 3:
$sort_links .= '<li>created_Time</td><td>Description</li>';
$sort_links .= '<li>Title</td><td>Description</li>';
break;
default:
$sort_links .= '<li>created_Time</td><td>Description</li>';
}
return $sort_links;
}//end of generate_sort_links
// This function builds navigational page links based on the current page and the number of pages
function generate_page_links($user_search, $sort, $cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "previous" link
if($cur_page >1){
$page_links .= '<- ';
}else{
$page_links .= '<- ';
}
// Loop through the pages generating the page number links
//loop through all the pages
for($i = 1; $i <= $num_pages; $i++){
if($cur_page == $i){
$page_links .= ' ' . $i;
//if current page, get rid of the url
}else{
$page_links .= ' ' . $i . '';
//if not current page, add the url to make it point to next page or previous page
}
}
//// If this page is not the last page, generate the "next" link
if($cur_page < $num_pages){
$page_links .= ' ->';
//if not last page, make -> have a url and can point to the previous one
}else{
$page_links .= ' ->';
}
return $page_links;
}//end of generate_page_links function
// Grab the sort setting and search keywords from the URL using GET
$sort = $_GET['sort'];
$user_search = $_GET['usersearch'];
//// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
$result_per_page = 5;// number of results per page
$skip = (($cur_page -1) * $results_per_page);
// Start generating the search results
echo '<div class="filter">';
echo generate_sort_links($user_search, $sort);
echo '</div>';
// Connect to the database
require_once('dbinfo.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Query to get the total results
$query = build_query($user_search, $sort);
$result = mysqli_query($dbc, $query);
$total = mysqli_num_rows($result);
$num_pages = ceil($total / $results_per_page);
// // Query again to get just the subset of results
$query = $query . " LIMIT $skip, $results_per_page";
//limit 10,5 means skip the 10 and return 5
//$skip = (($cur_page -1) * $results_per_page);
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
echo '<div class="search_item">';
echo '<div>' . $row['title'] . '</div>';
echo '<div>' . $row['created_at'] . '</div>';
echo '<div>' . substr($row['content'], 0,300) . '</div>';
echo '</div>';//end of search_item wrap
}
// Generate navigational page links if we have more than one page
if($num_pages >1 ){
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
}
mysqli_close($dbc);
Here you can find an easy way to do an infinite scroll:
JS:
var callback = function test() {
// Log how the height increases to the console
console.log(document.getElementById('infinite').style.height)
// equivalent to $('#infinite') in jQuery
var el = document.getElementById('infinite');
var newHeight = document.getElementById('infinite').offsetHeight + 200;
// Update the height property of the selected element
el.style.height = newHeight + 'px';
}
window.addEventListener('scroll', callback, false);
Basically adding an event listener attached to the scroll, so, every time we scroll, that function is triggered and increase the height property of the element.
You will just need a div as:
<div id='infinite' style='height: 2000px'></div>
Here's a fiddle
Hope it helps :)
What you need to do is an Ajax call on scroll, which appends the products. This question has been asked before and answered over here: On Scroll down how to make ajax call and get the respone data
The code executes an ajax call when a user reaches at end of page. By keeping track of the amount of products, you could send the offset and limit with the ajax call so you could use that within your database query.
EDIT:
Look what I just found: http://www.smarttutorials.net/infinite-scroll-using-jquery-ajax-php-and-mysql/ If this doesn't help...
EDIT 2:
No wordpress so code removed

how to load more images from a folder using php jquery ajax

i have multiple folders and all folders contain some images upto 20 images.
in my html page i want to show first 5 images and show click to view more 15
and when the user click that link it will show next 15 images
but till now i can only fetch all the images at a time
here is my code
<?php
$dirname = "img/outlets/".$service_type."/". $outlet_name ."/snaps/";
$images = glob($dirname."*.jpg");
foreach($images as $image)
{
?>
<a href="<?php echo $image ?>" class="imageHover">
<img src="<?php echo $image ?>" class="img-responsive" />
</a>
<?php
}
?>
I am sorry for not being supportive or all but I think you should ask or research about "pagination". What you are asking is a definition of pagination.
Actually you are asking , "How do I implement pagination ?"
http://codular.com/implementing-pagination
http://code.tutsplus.com/tutorials/how-to-paginate-data-with-php--net-2928
and here is some code you can try to implement simple pagination
try {
// Find out how many items are in the table
$total = $dbh->query('
SELECT
COUNT(*)
FROM
table
')->fetchColumn();
// How many items to list per page
$limit = 20;
// 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, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
// Prepare the paged query
$stmt = $dbh->prepare('
SELECT
*
FROM
table
ORDER BY
name
LIMIT
:limit
OFFSET
:offset
');
// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo '<p>', $row['name'], '</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
Simple PHP Pagination script
If I understood you correctly, you want your first page to display 5 images. Then, after clicking on a link, you want the same page to show the remaining images (from 5 up until the number of images in the folder – maybe 20 in your case).
I've been a bit verbose just so that it's clear. I've also left you echoing file paths as your code specifies, but presumably you're going to want to turn these into URLs. I'll leave that to you.
Try something like this:
<?php
$dirname = "img/outlets/".$service_type."/". $outlet_name ."/snaps/";
$images = glob($dirname."*.jpg");
$initial_images = 5; // However many you want to display on the inital load
// Get the starting image and the end image array keys
if($_GET['show_all_images']){ // Check the the browser sent a query parameter
// We've been asked to display more
// Get the array index of the first image. Remember that arrays start at 0, so subtract 1
$first_image_index = $initial_images - 1;
// Get the array index of the last image
$last_image_index = count($images);
}
else{
// We're on the inital load
$first_image_index = 0;
$last_image_index = $initial_images - 1;
}
// Iterate the glob using for. We want to specify an array key, so it's easier here to use for rather than foreach (which is the right solution most of the time)
for ($i=$first_image_index; $i < $last_image_index; $i++):?>
<a href="<?php echo $images[$i] ?>" class="imageHover">
<img src="<?php echo $images[$i] ?>" class="img-responsive" />
</a>
<?php endfor;?>
<?php if($_GET['show_all_images']): // Display a 'show less' link?>
Show less
<?php else: ?>
Show more
<?php endif; ?>
A simple way is to name images to end with indexed. Example being img_1.
You can then use ajax to fetch the last 15 images when user clicks on view more.
But this approach is very basic and is not scalable. As other answers suggest you can mix pagination with indexed image name approach

How to insert value into one cell mysql database according to which page the user is at?

I have a system set up that will display certain pages. I have the paignation set up already. In each page, I want to have 5 radio buttons, each named as "Definitely No", "No", "Second look", "Yes", "Definitely Yes". When the user clicks one of the radio button, php should insert one value (1-5) to a column called "viewed" and a row according to the current page variable ($currentpage). The paignation and each page's code is here:
<?php
// database connection info
require_once "connect_database_viewer.php";
$table = 'JOBARXXX20140709';
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM $table";
$result = $db_server->query($sql) or trigger_error("SQL", E_USER_ERROR);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = $numrows;
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
$query = "SELECT * FROM $table";
$result = $db_server->query($query);
if (!$result) die ("Database access failed: " . $db_server->error);
$rows = $result->num_rows;
$result->data_seek($currentpage);
echo $currentpage;
$row = $result->fetch_array(MYSQLI_NUM);
$asin = $row[2];
echo $asin;
echo file_get_contents("http://www.amazon.com//dp/$asin/?ie=UTF8");
echo <<<_END
<html>
<head>
<meta charset="=utf-8">
</head>
<body>
<div>
<iframe src="http://camelcamelcamel.com/product/$asin" width="1200" height="2300" align="middle"></iframe>
</div>
<div>
<form action="insert.php">
<input type="radio" name="result" value="1">Definitely No<hr>
<input type="radio" name="result" value="2">No<hr>
<input type="radio" name="result" value="3">Second Look<hr>
<input type="radio" name="result" value="4">Yes<hr>
<input type="radio" name="result" value="5">Definitely Yes<hr>
</form>
</div>
</body>
</html>
_END;
echo $currentpage;
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
How should I write the insert.php? This is a little insert code I wrote but I don't think it is working out.
if(isset($_POST['result']) && !empty($_POST['result'])){
$radioContent= $_POST['result'];
$sql = "UPDATE $table SET viewed='1' WHERE name='$currentpage'";
}
else{
error_log($mysqli->error);
}
}
A few things:
If you want to use the $_POST array, make sure to set your form method to post. <form action="insert.php" method="post"> The form element defaults to using GET.
$table and $currentpage will not be set in insert.php. You will have to send this information with your post. This can be done by making hidden inputs. <input type="hidden" value="<?php echo $currentpage ?>" name="currentpage" />. Now these variables will be accessible in the $_POST array. ($_POST['currentpage'])
ALWAYS escape any data being used for SQL queries. Including the hidden values made in #2. http://php.net/manual/en/mysqli.real-escape-string.php
You need to actually send the query to the database. As it is, you're only setting up the query string.

PHP form dynamic inputs

Very new to php... bear with me!
I'm creating a photography website and am stuck on a particular page. Ultimately I need the page to be a form with a dynamic number of inputs. It will be a dynamic visual representation of folders (or "galleries") on my web host server. Each div block will contain the first image from the folder along with the name of the folder - the heading text and image should both be clickable and act as a submit button to continue to the album.php page, passing the name of the folder via a GET method.
The first problem I had was trying to get rid of the submit button from a form, and replace with my album thumbnail and album title in an <a> tag. Apparently via javascript, and I managed to get this to work - kind of. I've gotten the page to a state where there is a form, with multiple inputs, but every single folder name is now being passed in the URL (e.g. mywebsite.com/album.php?name=album1&name=album2&name=album3) and I'm absolutely stuck!
The code is included, so if someone could have a look over and offer some guidance or point me in the right direction (and offer any other newbie tips!) it would be much appreciated.
Cheers
Lee
<form id="album" method="get" action="album.php">
<?php
$basepath = 'images/portfolios/public/';
$results = scandir($basepath);
foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;
if (is_dir($basepath . '/' . $result)) {
//create new gallery for each folder
?>
<div class="gallery">
<?php
//get count of images in folder
$i = 0;
$path = 'images/portfolios/public/' . $result;
if ($handle = opendir($path)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($path.$file))
$i++;
}
}
//create array, and choose first file for thumbnail
$files = array();
$dir = opendir($path);
while(($file = readdir($dir)) !== false)
{
if($file !== '.' && $file !== '..' && !is_dir($file))
{$files[] = $file;}
}
closedir($dir);
sort($files);
//form input - album name for next page
echo '<input type="hidden" name="name" id="name" value="'.$result.'" />';
//the headline and image link for gallery
echo '<a href="javascript: submitform()">' . $result . ' - ('.$i.' images)<br>
<img src="'.$path.'/'.$files[0].'" />
</a>';
?>
</div> <!-- end gallery -->
<?php }
}
?>
</form>
<script type="text/javascript">
function submitform(){document.forms["album"].submit();}
</script>
change your code from:
echo '<a href="javascript: submitform()">' . $result . ' - ('.$i.' images)<br>
<img src="'.$path.'/'.$files[0].'" />
</a>';
to this code:
echo '<a href="admin.php?name='.$result.'">' . $result . ' - ('.$i.' images)<br>
<img src="'.$path.'/'.$files[0].'" />
</a>';

Categories

Resources