<?php if (isset($_GET['p'])) { $variable = $_GET['p']; ?>
<?php if ($variable == '1'): ?>
<?php include('pages/home.php');?>
<?php endif;?>
<?php };?>
<?php if (isset($_GET['p'])) { $variable = $_GET['p']; ?>
<?php if ($variable == '2'):
include('pages/about.php');
else: include('pages/home.php'); endif; };?>
The above is what I have used to try and fix it, but if I don't put it, errors show up. For example if I used "ifelse", and it tells me to change it to else, or endif. But when I use endif, it tells me to use ifelse. I'm trying to make it so http://localhost/?p=PAGE_ID just simply shows the page using an include(FILE_PATH) statement.
Does anyone know where I went wrong? Or how I can fix it :)
You seem to have thoroughly tied yourself in knots. To my mind, this is a much cleanrer and more flexible and maintainable way to approach the whole thing:
$pages = [
"1" => "pages/home.php",
"2" => "pages/about.php"
];
if (isset($_GET['p'])) {
if (isset($pages[$_GET['p']]))
{
$page = $pages[$_GET['p']];
}
else
{
$page = $pages["1"];
}
}
else
{
$page = $pages["1"];
}
include($page);
This way, you have a list of pages, and the system simply looks up the required page in the array by its index number (as passed in via the GET parameter). If it can't find that index, it just uses the default page.
You can now easily add pages by just adding items to the array, without needing to write more if/else logic. You could even store the array data in a database instead of it being hard-coded.
You dont need or want an elseif in this flow, simple do
<?php
if (isset($_GET['p'])) {
if ($_GET['p'] == '1') {
include('pages/home.php');
}
if ($_GET['p'] == '2') {
include('pages/about.php');
}
}
If the value of $_GET['p'] can only be 1 or 2 you could do
<?php
if (isset($_GET['p'])) {
if ($_GET['p'] == '1') {
include('pages/home.php');
} else {
include('pages/about.php');
}
}
Or if $_GET['p'] could be multiple values a switch may be more useful
<?php
if (isset($_GET['p'])) {
switch($_GET['p']) {
case 1:
include('pages/home.php');
break;
case 2:
include('pages/about.php');
break;
default:
include('pages/somethingelse.php');
}
}
Note I also left out the intermediate variable, as its not needed. The $_GET and $_POST arrays are, once filled by PHP all yours to use as you want. There is no need to waste CPU cycles and memory creating unnecessary variables
Related
I'm trying to pull in the parameter of a URL and use that to determine what information to display on page, but for some reason the information is being read wrong. The first thing I do is check for the parameter below and assign it to $page
<?php
if(isset($_GET["page"])) {
$page=$_GET["page"];
}
?>
I then check if the $page is equal to 2 or 3. For some reason, if I echo out $page, I get the proper value of the parameter but it displays incorrect info.
<?php
if(isset($page) == '2') { ?>
DISPLAY INFO A
ECHO $PAGE RETURNS 2
<?php } elseif(isset($page) == '3') { ?>
DISPLAY INFO B
ECHO $PAGE RETURNS 3
<?php } else { something here } ?>
For some reason, even though $page returns 3, I receive INFO A that's supposed to be displayed on page 2. Am I pulling the parameter wrong? The URL Looks like this:
feed.php?page=3
php isset function return Boolean.
You should change code to:
<?php
if(isset($page) && $page== '2') {
?>
DISPLAY INFO A
ECHO $PAGE RETURNS 2
<?php } elseif(isset($page) && $page== '3') { ?>
DISPLAY INFO B
ECHO $PAGE RETURNS 3
<?php } else { something here } ?>
This is wrong:
if(isset($page) == '2') {
It should be
if( $page == '2') {
This will only seem to work on page 1, because isset($page) returns true, which truthy gets converted to 1. The isset() function is only to check if the variable has been set or not
if($page == '3')
Why the isset()? You already do that when you assign it. Maybe this as well:
if(isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page = '0'; // or something
}
isset() return a TRUE/FALSE, yet you're comparing it against normal integers. Boolean TRUE in mysql is equivalent to integer 1, but will fail the rest of your tests. You need to have:
if (isset($_GET['page'])) {
if ($_GET['page'] == 1) { ... 1 stuff }
else if ($_GET['page'] == 2) { ... 2 stuff }
}
I've made a simple index.php script for my homepage, however, it won't work.
<?php
$Query = $_GET['p']
if (strtolower($Query) == "about") {
include("About.php")
die()
}
if (strtolower($Query) == "") {
include("Home.php")
die()
}
if ($Query) {
include("Home.php")
die()
}
?>
It's my first time coding in php so i don't know what is wrong.
First you need simicolons. Second, why die? Why not do something like.
<?php
$Query = $_GET['p']
if (strtolower($Query) == "about") {
include("About.php");
} else {
include("Home.php");
}
?>
I have submitted some code to the redirected url and now trying to use this to echo some information out but can't figure out where I am going wrong.
I have the following code:
<?php $login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt) == '1'{
return 'failed';
}
?>
all I want to do is if the url has $login_attempt=1 I want to return the message 'failed' to the page.
There is no point of escaping anything if it doesn't enter anywhere important (like a database).
<?php
if ($_GET['login_attempt'] == '1') {
echo 'failed';
}
?>
Also, you have a problem in your if statement, that's corrected in the code above. Be sure to include all of the condition inside of parenthesis, and not just one side of the equality check.
Also, if you wish to display something on the screen, you should echo it, not return.
how about:
if ($login_attempt == '1'){
echo 'failed';
}
Try this one. Your error in $login_attempt == '1':
<?php $login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt == '1'){
echo 'failed';
return false;
}
?>
As others already mentioned you have several problems but the syntax error comes from this:
if ($login_attempt) == '1'{
it should be
if ($login_attempt == '1') {
Dont u think if ($login_attempt) == '1' should be something like this ($login_attempt == '1') Sorry...many others also suggested this :P
At the first, I must tell you that you have a mistake in your IF condition. You typed == outside of ().
In addition, you have to be aware of status of setting your variable through your URL. Check the code below. In this code, I made a function to check the status. Default status is true, and we will check it just for a negative condition. I hope it could be useful for you:
<?php
function check() {
if (isset($_GET['login_attempt'])) {
$login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt == '1') {
return false;
} else {
return true;
}
} else {
return true;
}
}
if (!check()) echo('Error Message');
?>
I'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.
I have a bit of a problem with my PHP code, I am assigning values to variables in different states of the flow depending on what I receive, but for some reason it keeps getting stuck at one point, here is the code.
if (isset($session)) {
//if the user is in the database
if ($row == 1) {
$from = $_GET['from'];
if (isset($from)) {
$page = $_GET['page'];
switch ($page) {
case "game":
$page = "game";
sendVars($page);//send the variable
break;
case "gallery":
$page = "gallery";
sendVars($page);//send the variable
break;
case "leaderboard":
$page = "leaderboard";
sendVars($page);//send the Variable
break;
}
}else {
$page = "game";
sendVars($page);//send the variable
}
//if the user is not in the database
}else {
//do this
}
} else {
//register
}
Now for some odd reason, it keeps setting the value of $page to game, even though I set the page variable to gallery like so http://www.mydomai.com/?from=set&page=gallery . the only reason for this that I can think of is that my switch is not working as it should? or it is bypassing the switch somehow?
Thanx in advance!
I just ran your code after removing a few of the unessersary variable assignments:
<?php
// I added this function just for testing
function sendVars($page) {
echo $page;
}
if (isset($_GET['from'])) {
$page = $_GET['page'];
switch ($page) {
case "game":
sendVars($page); //send the variable
break;
case "gallery":
sendVars($page); //send the variable
break;
case "leaderboard":
sendVars($page); //send the Variable
break;
}
} else {
$page = "game";
sendVars($page); //send the variable
}
And it all seems fine, xxx.php?from=1&page=gallery echos out "gallery", try doing a print_r($_GET) at the top of your script and see what it prints out and let us know.
On a side note I think the below may be shorter for you and still do the same thing:
if (isset($_GET['from'])) {
// Check if $_GET['page'] exsists and is either game, gallery or leaderboard
if (isset($_GET['page']) && in_array($_GET['page'], array('game', 'gallery', 'leaderboard')))
sendVars($_GET['page']);
}
else
sendVars('game');
I hope this helps
Cheers
Luke
Try doing a var_dump($page);exit; before the switch and see what it spits out.
Also you can do a var_dump($from) and see what that is spitting out - it may be that it goes to the else, so it may not even be getting to the switch.
If this is inside a function, I personally prefer guard-style clauses than constantly increasing the levels of indentation. The idea is you pick out the bad conditions (ie if something is going wrong) to "protect" the larger block of logic.
In your case that's the switch statement.
if (!isset($session))
return ...; // register
if ($row != 1)
return ...; // do this
$from = $_GET['from'];
$page = $_GET['page'];
if (isset($from)) switch ($page) {
case "game":
$page = "game";
break;
case "gallery":
$page = "gallery";
break;
case "leaderboard":
$page = "leaderboard";
break;
}
else $page = "game";
return sendVars($page);// don't need to repeat this if all cases do it!
It's just a style of code and it's not going to fix all (if any) of your problems. You actually don't need the switch block in there for this code. I can't see that it's doing anything.
You don't necessarily need the switch statement. I can't see an obvious problem with your logic but I think this will do the same thing:
if (isset($session))
{
//if the user is in the database
if ($row == 1)
{
$page = (in_array($_GET['page'],array('game','gallery','leaderboard'))) ? $_GET['page'] : "game";
sendVars($page); //send the variable
}
else //if the user is not in the database
{
//do this
}
}
else
{
//register
}
Just saw Luke used the same in_array method but 25 mins before me. Serves me right for being slow!