Need some PHP assistance - php

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...
}

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;
}

Why does this undefined error occur when storing the first number to a $_SESSION[] variable?

I'm making a mini shopping cart for my project. Im storing the number of items chosen by the user, I don't understand that when i add one to my session variable I always get this error on the first go
Undefined index: cart_1 in D:\wamp\www\MiniCart\cart.php on line 100
And when I add again or refresh the same page it works fine. Why could this error be coming up? I removed the +=1 from the statement and it worked fine, apparently there is no syntax error too.
Cart.php
<!DOCTYPE>
<html>
<head></head>
<body>
<?php
session_start();
//The page where to jump to after adding/editing cart.
$page = 'mini_cart_index.php';
$link = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
echo "Error:".mysqli_connect_error();
echo "<br/>";
} else {
echo "Connected to SQL<br/>";
}
//==================================================
if(isset($_GET['add']))
{
$obt=$_GET['add'];
$quantity_limit = 'SELECT id,quantity FROM products WHERE id='.mysqli_real_escape_string($link,(int)$_GET['add']);
$quantity = mysqli_query($link,$quantity_limit);
while($quantity_row=mysqli_fetch_assoc($quantity))
{
if($quantity_row['quantity']!=$_SESSION['cart_'.$_GET['add']])
{
$_SESSION['cart_'.$_GET['add']]+='1';
}
}
/*
echo 'id='.$obt.' '.'next<br/>';
echo 'Now storing info into session variable and adding one<br/>';
echo $_SESSION['cart_'.$_GET['add']];
echo '<br/>';
echo 'info stored<br/>';
*/
}
//***************************************************
function products()
{
GLOBAL $link;
$get ="SELECT id,name,description,price FROM products
WHERE quantity > 0 ORDER by id ASC";
if($result=mysqli_query($link,$get))
{
echo "Data Selected to be displayed<br/>";
} else {
echo "Error:".mysqli_error($link);
}
if(mysqli_num_rows($result)==0)
{
echo "There are no products to display!<br/>";
} else {
while($get_row=mysqli_fetch_assoc($result))
{
echo '<hr/><br/>';
echo 'displaying data from database<br/>';
echo '==================================';
echo '<p>'.$get_row['name'].'<br/>'.
$get_row['description'].'<br/>'.
number_format($get_row['price'],2).
' Add'.'</p>';
echo '<hr/><br/>';
}
}
}
echo 'outside'.$_SESSION['cart_1'];
?>
</body>
</html>
Mini_cart_index.php
<?php require 'cart.php';?>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<?php products() ?>
</body>
</html>
That code is filled with SQL injection vulnerabilities, you should use PDO and prepare your statements.
PHP is warning you because it has to read the current value and add to it, but the first time you try to access it doesn't exist.
You could suppress the warning with:
#$_SESSION['cart_'.$_GET['add']]+='1';
A better way to do it though would be checking if it exists first
$name = 'cart_'.$_GET['add'];
if(isset($_SESSION[$name]) {
$_SESSION[$name] = 1;
} else {
$_SESSION[$name] += 1;
}
The problem is caused by the fact that...
$var['abc'] += 1
...is the same as
$var['abc'] = $var['abc'] + 1
So if you've got a clean session and $var['abc'] doesn't exist, you're going to get a warning because you're trying to read a non-existant value in order to add 1 to it.
While it's true that 0 + 1 = 1
...what's actually happening here is undefined + 1 = 1 with a warning.
As other answers have mentioned - to fix the issue, you can explicitly check that the array index exists before trying to increment it.
I'd do that with the ternary operator like this:
$key = 'card_' . $_GET['add'];
$_SESSION[$key] = (isset($_SESSION[$key]) ? $_SESSION[$key] : 0) + 1;
This is effectively saying
$val = ($val if it exists, otherwise 0) + 1;
Change your if statement to check if it's empty too:
if (!isset($_SESSION['cart_'.$_GET['add']])) {
$_SESSION['cart_'.$_GET['add']] = 1;
} elseif ($quantity_row['quantity'] != $_SESSION['cart_'.$_GET['add']]) {
$_SESSION['cart_'.$_GET['add']] += 1;
}

How to make current page with different style (PHP ?page href)?

My piece of code.
And problem now are about styling, i just want style page number, wich is open, like a active id, if page open, then that number is in different color or smth else.
I need make a new variable? Or what, i just try to add but its wont work, it only works if at the end i write echo $page; , then it show style on this, but i need on links, numbers.
<?php
if($total_pages > 1){
if($page != 1){
echo ' < ';
}
for($number=1;$number<=$total_pages;$number++)
{
echo ''.$number.'';
}
if($page != $total_pages){
echo ' > ';
}
}
?>
You can do something like this.
$currentPageNumber = $_GET['page'];
for($number=1;$number<=$total_pages;$number++){
$currentPageStyle = '';
if($number == $currentPageNumber){
$currentPageStyle = 'style="color:red"';
}
echo '<a href="?page='.$number.'" '.$currentPageStyle.'>'.$number.'</a>';
}

Weird problem with PHP Breadcrumb Script

I'm using Mick Sears' php breadcrumb script - found here:
http://www.roscripts.com/PHP_breadcrumbs-118.html
I've used this script several times with no problems. But with this one site I'm having the weirdest problem... Home page - fine. Level 1 page - fine. But every time I move to a level2 page, the correct level1 crumb is replaced by "Help". The link on the crumb is the correct one for the help page. This happens even if I clear all browser caches and don't go to the Help section of the site at all.
The site is http://www.fastexas.org. The script is there, but I gave the breadcrumb div display:none; until I can figure this out.
This script seems to have been around awhile and I'm wondering if anyone else has seen this problem.
The Breadcrumb Script:
<?php
class Breadcrumb{
var $output;
var $crumbs = array();
var $location;
function Breadcrumb(){
if ($_SESSION['breadcrumb'] != null){
$this->crumbs = $_SESSION['breadcrumb'];} }
function add($label, $url, $level){
$crumb = array();
$crumb['label'] = $label;
$crumb['url'] = $url;
if ($crumb['label'] != null && $crumb['url'] != null && isset($level)){
while(count($this->crumbs) > $level){
array_pop($this->crumbs); }
if (!isset($this->crumbs[0]) && $level > 0){
$this->crumbs[0]['url'] = "/index.php";
$this->crumbs[0]['label'] = "Home";}
$this->crumbs[$level] = $crumb;}
$_SESSION['breadcrumb'] = $this->crumbs;
$this->crumbs[$level]['url'] = null;}
function output(){
echo "<ul>";
foreach ($this->crumbs as $crumb){
if ($crumb['url'] != null){
echo "<li> <a href='".$crumb['url']."' title='".$crumb['label']."'>".$crumb['label']."</a></li> ";} else {
echo "<li class='last'>".$crumb['label']."</li> ";}}
echo "</ul>";}}
?>
Each page begins with something like:
<?php session_start();
$level= '1';
$label= 'Honors Circle';
$url= '/honors/'; include($_SERVER['DOCUMENT_ROOT']."/includes/Breadcrumb.php");
$trail = new Breadcrumb();
$trail->add($label, $url, $level); ?>
or
<?php
session_start();
$level= '2';
$label= 'Districts';
$url= '/honors/district.php';
include($_SERVER['DOCUMENT_ROOT']."/includes/Breadcrumb.php");
$trail = new Breadcrumb();
$trail->add($label, $url, $level);
?>
And to print the breadcrumb trail:
<div id="breadcrumb"><?php $trail->output(); ?></div>

If-statement: how to pull 2nd GET variable

How do I get this to pull my 2nd variable? (I already have a switch setup)
<body id="<?php if (! isset($_GET['page'])) { echo "home"; } else { $_GET['page']; echo $page; } ?>">
I have a switch statement that pulls the pages from
index.php?page=#####
and I have just added this part to my switch:
index.php?page=####&section=#####
Right now, if I am on page=photos, my code ends up being:
<body id="photos">
I need to make it so that if any link has the "sections" variable on it like this page=photos&section=cars it uses the same ID:
<body id="photos">
First of all, a HTML element can only have one id. So if you want to create a hybrid (e.g. page-section) you can do something like this:
<body id="<?php echo isset($_GET['page']) ? $_GET['page'] : "home"; echo isset($_GET['section']) ? ("-".$_GET['section']) : ''; ?>">
For more information on Ternary Operators in PHP (the ? and : I used in the echo statement) see http://php.net/manual/en/language.operators.comparison.php
I am not entirely sure I understand your question, but where you're doing:
$_GET['page']; echo $page;
What do you think is happening? You're echoing a variable that has no definition. If you want to echo the value passed in the url, just do:
echo $_GET['page'];
GET doesnt mean your getting the varible, its the method by which the variable was passed to he page. The possible methods are get (in the url) or post (not).
Wouldn't that be an if to find out it if the section was defined? i.e.
if(isset($_GET['section'])){
//create div
} elseif(isset($_GET['page']){
//create fallback div
}
Move the PHP code outside the body's id attribute for readability, and use else if. Make sure your code isn't vulnerable to injection by sanitizing or validating input from $_GET. For example:
<?php
function isValidID($x) {
return preg_match('/^[A-Z][-_.A-Za-z0-9]$/i', $x);
}
if (isset($_GET['section']) && isValidID($_GET['section'])) {
$bodyID = $_GET['section'];
} else if (isset($_GET['page']) && isValidID($_GET['page'])) {
$bodyID = $_GET['page'];
} else {
$bodyID = 'home';
}
?>
...
<body id="<?php echo $bodyID; ?>">
Alternatively,
<?php
function isValidID($x) {
return preg_match('/^[A-Z][-_.A-Za-z0-9]$/i', $x);
}
$bodyID='home';
foreach (array('section', 'home') as $key) {
if (isset($_GET[$key]) && isValidID($_GET[$key])) {
$bodyID = $_GET[$key];
break;
}
}
?>
...
<body id="<?php echo $bodyID; ?>">
In this case, I'd use the first, unrolled version. If you had to check more input keys, use the loop-based approach.
If you decide you want both page & section in the ID, you can try something like:
<?php
function isValidID($x) {
return preg_match('/^[A-Z][-_.A-Za-z0-9]$/i', $x);
}
if (isset($_GET['page']) && isValidID($_GET['page'])) {
$bodyID = $_GET['page'];
} else {
$bodyID = 'home';
}
if (isset($_GET['section']) && isValidID($_GET['section'])) {
$bodyID .= '_' . $_GET['section'];
}
?>
...
<body id="<?php echo $bodyID; ?>">

Categories