How to increase/decrease the number in $_GET variable link? - php

I have a PHP page that utilizes a $_GET variable, "link", to display a specific image on the page. My PHP page URLs look like "website.com/page.php?link=1"
PHP Code:
$link = $_GET['link'];
if($link == 1) { $linkURL = "http://website.com/image1.jpg";}
if($link == 2) { $linkURL = "http://website.com/image2.jpg";}
if($link == 3) { $linkURL = "http://website.com/image3.jpg";}
HTML
<img src="<?=$linkURL;?>"></img>
I want to add 'Next' and 'Previous' buttons on this page, which will go to the next/previous $link URL when clicked.
<a class="prevBtn" href="">Previous</a>
<a class="nextBtn" href="">Next/a>
What should I put as the href in order to achieve this? Basically, I want it to be "$link -1" for previous and "$link +1" for next.
Thanks in advance for the help!

Assuming your images will always be image1.jpg, image2.jpg, image3.jpg etc, you can achieve what you're looking for like this:
Note: I used PHP only just so it's easier to follow the logic
<?php
//Check $_GET variable exists otherwise set it to a default value = 1
if(isset($_GET['link'])) {
$link = $_GET['link'];
} else {
$link = 1;
}
if($link == 1) { $linkURL = "http://website.com/image1.jpg";}
if($link == 2) { $linkURL = "http://website.com/image2.jpg";}
if($link == 3) { $linkURL = "http://website.com/image3.jpg";}
// Set variables for the previous and next links
$prev = $link-1;
$next = $link+1;
//Display your image
echo "<img src='".$linkURL."'></img>";
//Only show the previous button if it's NOT the first image
if($prev!=0){
echo "<a class='prevBtn' href='http://website.com/page.php?link=".$prev."'>Previous</a>";
}
//Only show the next button if it's NOT the last image
if($next<=3){
echo "<a class='nextBtn' href='http://website.com/page.php?link=".$next."'>Next</a>";
}
?>

You try can pass the parameters through url as
<a class="prevBtn" href="<?php echo $linkURL?>?link=-1">Previous</a>
<a class="nextBtn" href="<?php echo $linkURL?>?link=+1">Next/a>

An alternative way of doing this would be to use an array. The advantage of this is you can just add new images to the array and it will still work. You don't have to worry about editing the other if statements around the next button.
<?php
//Check $_GET variable exists otherwise set it to a default value = 1
$images = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
if(isset($_GET['link']) {
$link = $_GET['link'];
} else {
$link = 0;
}
if(!$images[$link]) {
$link=0;
}
// Set variables for the previous and next links
$prev = $link-1;
$next = $link+1;
//Display your image
echo "<img src='http://website.com/".$images[$link]."'></img>";
//Only show the previous button if it's NOT the first image
if($prev<0){
echo "<a class='prevBtn' href='http://website.com/page.php?link=".$prev."'>Previous</a>";
}
//Only show the next button if it's NOT the last image
if($next!=count($images)){
echo "<a class='nextBtn' href='http://website.com/page.php?link=".$next."'>Next</a>";
}
?>

Related

How do I create a prev/next function for a one page display site?

I'm looking to create a function to display prev-next buttons on the header of a one page site.
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT 1";
The content for the entire site comes off a primary key in the database titled "issue_no" everything inside issue_no is the content to be displayed on the one page.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}
}
This is displayed on index.php
Currently, it displays the latest issue pending on the publish date, but I would like to add the function to go back to previous and next editions.
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Also - how would I go about making sure these each have clean URLs?
e.g. http://www.example.com/issue/023
Any help much appreciated.
I've tried reading up on pagination, but I'm finding it a little complicated to wrap my head around this one.
Thanks.
You say:
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Assuming (for example) an URL like “http://www.example.com/issue.php?issue=23” (for now postponed the ‘clean’ URL question) you can resolve all questions in this way:
$issueId = $_GET['issue'];
/* 01: Retrieve ALL id */
$result = $con->query( "SELECT GROUP_CONCAT( `issue_no` ORDER BY `issue_no` DESC ) FROM `issue`" );
$allId = explode( ',', $result->fetch( PDO::FETCH_NUM )[0] );
/* 02: Check if $issueId exists and set previous/next id */
$prev = $next = False;
$found = array_search( $key, $allId );
if( $found === False ) $found = count( $allId )-1;
if( $found > 0 ) $prev = $allId[$found-1];
if( $found < count($allId)-1 ) $next = $allId[$found+1];
/* 03: Retrieve current issue: */
$result = $con->query( "SELECT * FROM `issue` WHERE `issue_no` = '{$allId[$found]}'" );
$row = $result->fetch_assoc();
/* 04: Output previous/next page link: */
if( $prev !== False ) echo "Prev Page";
else echo "<span class=\"inactive\">Prev Page</span>";
if( $next !== False ) echo "Next Page";
else echo "<span class=\"inactive\">Next Page</span>";
// Your code from here
Code above is only as example. By this way, all issue_no are stored in $allId variable, so you can easy implement also the dropdown menu. The issue_no fields are retrieved in descending order, if you prefer ascending you can change first query (#01) in ORDER BY issue_no ASC.
Note that if the user don't ask for any specific issue (i.e. calling http://www.example.com/issue.php), the current issue is set to first array value of $allId (#02): if you prefer to produce an alert like “This issue doesn't exists” you have to modify the script in this way:
$found = array_search( $key, $allId );
if( $found === False )
{
// Your error routine here
}
else
{
if( $found > 0 ) $prev = $allId[$found-1];
(...)
}
In the output of previous/next page URLs (#04), I use a basic <a href> tag, but you can use buttons.
Clean URLs
I strongly recommend to produce first a full working code ignoring the ‘clean’ URL question. Then, all you will need to change will be only one row.
By the way, to activate clean urls, you have to modify the .htaccess file of your site in a way like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^issue/.*$ /issue.php [NC,L]
</IfModule>
then, in your issue.php script, you have to change $issueId = $_GET['issue']; with:
$issueId = array_pop( explode( '/', $_SERVER['REQUEST_URI'] ) );
This RewriteRule is only an example, actually I think you are interested in clean URLs for all your site, so the best solution can be to redirect all incoming URLs to a redirect.php that process the REQUEST_URI and include appropriate page or echoes ‘Not Found’ message.
Here you can find more about basics on RewriteRule
These code I haven't tested, not stable at all. You have to optimize it.
Function to get data
In PHP:
<?php
$issueno = $_GET["issueno"];
if($issueno == null){
$issueno = 0;
}
$servername = "localhost";
$username = "username";
$password = "password";
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT " + $issueno + ",1";
if($row = mysqli->query($query, MYSQLI_USE_RESULT))
{
/* row is the row selected */
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}else{
echo "It does not exist";
}
$mysqli->close();
?>
NEXT
In Javascript, by redirecting with a issueno parameter
function next(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
//Added 1 here as NEXT
currentissueno = 0;
}
//Maximum issues No. OutOfBounds not handled... I have to sleep now
currentissueno++;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
PREVIOUS
In Javascript, by redirecting with a issueno parameter
function prev(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
alert("The last previous page");
return;
}
currentissueno--;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
Function to GET url parameter
Required. From Using the GET parameter of a URL in JavaScript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return null;
}

How to pass an URL to a <a href="">

I'm still new to php and I've made a script that checks the language of the website and if it's English set's the button link to an english page and else to another page.
Here goes:
<?php
$link1 = "http://www.uvt.ro/ro/accesibilitate/";
$link2 = "http://www.uvt.ro/en/accesibilitate/";
$url = "";
if($_SESSION["lang"]->lang!="ro"){
$url = $link2;
}
else {
$url = $link1;
}
?>
Button
It's supposed to be simple, I don't know why it doesn't work.
You'd echo the $url like so:
<?php
$link1 = "http://www.uvt.ro/ro/accesibilitate/";
$link2 = "http://www.uvt.ro/en/accesibilitate/";
$url = "";
if ($_SESSION["lang"]->lang != "ro") {
$url = $link2;
}
else {
$url = $link1;
}
?>
Button
You can condense the code to this using the ternary operator:
<?php
$link1 = "http://www.uvt.ro/ro/accesibilitate/";
$link2 = "http://www.uvt.ro/en/accesibilitate/";
$url = ($_SESSION["lang"]->lang != "ro") ? $link2 : $link1;
?>
Button
You have to echo $url in tag.
Button
Button
replace with:
Button
OR
Button
you can try this one:
See the page
<?php
$test = $_GET['p'];
?>
Test
or
Try like
HTML in PHP :
echo "<a href='".$link_address."'>Link</a>";
Or even you can try like
echo "<a href='$link_address'>Link</a>";
Or you can use PHP in HTML like
PHP in HTML :
Link

Need some PHP assistance

how do i tell this php code that, when there's not a ?page=randompage in the url, it will trow the active to index.php automatically?
<?php
$query = "SELECT pagename, pagetitle FROM pages LIMIT 8";
$result = $mysqli->query($query);
echo "<ul>";
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<li><a href=\"?page=".$row["pagename"]."\"";
if ($_GET['page'] == $row['pagename']) {
echo " class=\"active\""; } echo "> ".$row["pagetitle"]." </a></li>";
}
echo "</ul>";
?>
It's beacuse whenever my url looks like this http://localhost/greencph/ it shows a php error, because it does not know which site it is on, it works perfect as long as the url looks like this: http://localhost/greencph/?page=index.php a detailed explanation on how to fix this problem would be appreciated!
Please remember i'm a idiot, explain to me so i understand it. xD
The error is coming because, every time the value of $_GET is not getting set.
So, to deal with it,
get the value of $_GET['page'] in a variable.
So that, if we do not get $_GET, we will assign it a default value, that is index page.
$page = ! empty($_GET['page']) ? $_GET['page'] : 'index'; // set default value.
And change this line:
if ($page == $row['pagename']) {
So, the final modified code should be:
<?php
$query = "SELECT pagename, pagetitle FROM pages LIMIT 8";
$result = $mysqli->query($query);
$page = ! empty($_GET['page']) ? $_GET['page'] : 'index';
echo '<ul>';
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$class = '';
if ($page == $row['pagename']) {
$class = 'active';
}
echo '<li>' . $row["pagetitle"].' </li>';
}
echo "</ul>";
?>
Use the $_GET array:
<?php
if(isset($_GET['page'])) {
// Your code
...
}
?>
Problem is in this line
if ($_GET['page'] == $row['pagename']) {
You're not checking whether the index 'page' even exists. So, when you try to load the page without any GET parameters $_GET['page'] won't be even set and you'll get an error for accessing unset element.
To fix this simply check
if(isset($_GET['page']) {
...your code...
}

How to display all images when a link is clicked by using JQuery, PHP & MySQL?

I have this script that displays ten images or less by default but when a user clicks the <a> tag link it displays all the users images.
Is there a way I can display all the users images by having them slide down when a user clicks on the link <a> link instead of refreshing the page using JQuery or PHP?
Here is the php code.
if(isset($_GET['view']) && strlen($_GET['view']) == 1) {
$view = htmlentities(strip_tags($_GET['view']));
}
$multiple = FALSE;
$row_count = 0;
if(isset($view) == a) {
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'");
} else {
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'
LIMIT 0, 10");
}
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
if(($row_count % 5) == 0){
echo '<ul>';
}
echo '<li><img src="/images/thumbs/' . $row['avatar'] . '" /></li>';
if(($row_count % 5) == 4) {
$multiple = TRUE;
echo "</ul>";
} else {
$multiple = FALSE;
}
$row_count++;
}
if($multiple == FALSE) {
echo "</ul>";
}
}
echo 'View All';
Have a look at jquery's load
http://api.jquery.com/load/
Update:
if you see in the examples provided you can use:
$('#result').load('ajax/test.html');
where you substitute #result with the id of the element (a <div> for example) where you want put your images
and the 'ajax/test.html' where you put the url of the php code that creates the image list

PHP, MySQL & JQuery Question?

I have this script that displays all the users images which i will display below.
My question: Is there a way I can display the first 10 images in the MySQL database and have the script hide the rest of the users images until the user clicks the link View All and have the rest of the images slide down when the user clicks the link?
Here is my PHP & MySQL script?
$multiple = FALSE;
$row_count = 0;
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
if(($row_count % 5) == 0){
echo '<ul>';
}
echo '<li><img src="/images/thumbs/' . $row['url'] . '" /></li>';
if(($row_count % 5) == 4) {
$multiple = TRUE;
echo "</ul>";
} else {
$multiple = FALSE;
}
$row_count++;
}
if($multiple == FALSE) {
echo "</ul>";
}
}
echo 'View All';
Split the images into two parts. And set the second part to be hidden. Then add a click handler to slideDown. Here is the code:
UPDATE: it's not necessary to put the first 10 images into a div, but won't hurt either.
PHP
<?php
//echo '<div id="images">'; // visible images
while($row = mysqli_fetch_array($dbc)) {
// other stuff
// ...
// after the 10th image (0-9)
// open the hidden div
if ($i == 9) {
//echo '</div>'; // end of visible images
echo '<div id="hidden">'; // hidden images
}
}
echo '</div>'; // end of hidden
echo 'view all'; // view all
?>
jQuery
$(document).ready(function(){
$("#hidden").hide();
$("#view_all").click(function(){
$("#hidden").slideDown();
});
});
See it in action
Note: be sure not to hide the div with CSS. You do it in jQuery, and by this you allow users with JS disabled to get the content.
I'm not sure how many, or how large these images are, but if you want to make this scalable, I'd suggest doing an ajax callback that retrieves and fills in the "hidden" images, if the user requests them.
Yes, in your loop echoing out the list items, add the style="display:hidden" class="hidden" attribute when the count is > 10. Then use the window's scroll event to detect when the browser is scrolled near to the bottom of the window and then use jQuery to show the first hidden list item.
EDIT: This actually will show the items as the user scrolls down and does not need a "Show all button".
JQuery:
$(".hidden").hide();
$(window).scroll(function(){
if ($(window).scrollTop()+$(window).height > $("li:hidden:first").offset().top - SOMEPADDING )) {
$("li:hidden:first").fadeIn(200);
}
}

Categories