PHP Question: How to fix these if/elseif statements - php

I am trying to use these if/else if statements to display these php pages. The if/elseif statements allow for the php page to show up. The data is stored in the mysql. How do we get it so that if its already being displayed it only enters once? Thank you. I hope you can help. Sorry this is a little confusing. I just learned English recently.
Thank you.
if ($result_array[0] = Politics) {
require 'news/political.php';
} elseif ($result_array[0] = Gossip) {
require 'news/celebgossib';
} elseif ($result_array[0] = Entertainment) {
require 'news/entertainment.php';
} elseif ($result_array[0] = Finance) {
require 'news/finance.php';
} elseif ($result_array[0] = Health) {
require 'news/health.php';
} elseif ($result_array[0] = Leisure) {
require 'news/leisure.php';
} elseif ($result_array[0] = Sports) {
require 'news/sports.php';
} elseif ($result_array[0] = Tech) {
require 'news/tech.php';
} elseif ($result_array[0] = World) {
require 'news/world.php';
} else {
echo "There is no interests in your database";
}
if ($result_array[1] = Politics) {
require 'news/political.php';
} elseif ($result_array[1] = Gossip) {
require 'news/celebgossib';
} elseif ($result_array[1] = Entertainment) {
require 'news/entertainment.php';
} elseif ($result_array[1] = Finance) {
require 'news/finance.php';
} elseif ($result_array[1] = Health) {
require 'news/health.php';
} elseif ($result_array[1] = Leisure) {
require 'news/leisure.php';
} elseif ($result_array[1] = Sports) {
require 'news/sports.php';
} elseif ($result_array[1] = Tech) {
require 'news/tech.php';
} elseif ($result_array[1] = World) {
require 'news/world.php';
} else {
echo "There is no interests in your database";
}

Something like:
$pages = array(
'Politics' => 'political',
'Gossip' => 'celebgossib',
...
);
$used = array();
for ($i = 0; $i < 2; ++$i)
{
if (array_key_exists($result_array[$i], $pages)
{
if (!array_key_exists($result_array[$i], $used))
{
# only display this section once
include 'news/'.$pages[$result_array[$i]].'.php';
$used[$result_array[$i]] = true;
}
}
else
{
echo "Nothing to see here.";
}
}
I'm not sure exactly what you want to do if the page isn't found; or if subsequent records are duplicates.

You need to use == instead of =
I don't know what the right side of the statement is, for example Politics. If its not a variable then you should put it in quotes.
Something like this
if ($result_array[0] == "Politics") {
require 'news/political.php';
}else ...

It looks like you're iterating over an array of options, and including a bunch of set files?
I would try something like the following:
switch( TRUE )
{
case in_array("Politics", $result_array):
require 'news/political.php';
break;
case in_array("Gossip", $result_array):
require 'news/celebgossib';
break;
// etc.
}

How about using a switch statement?
switch $result_array[0] {
case 'Politics': include('politics.php'); break;
case 'This': include(...); break;
case 'That': include(....); break;
default: include('default.php'); break;
}
for a loooong set of if/then/else tests with simple "todo" sections, a switch statement is ideal.

Related

How to retrive multiple url parameter in php

I have 4 parameter in my URL. I retrieve the url parameter from my url that is given. With every parameter I'm changing the path to a directory and get different images.
My sample url look like this:
www.sample.com?cat=section1&language=de&prices=pl
The code is working but it's a spagheti code.
Is there a solution to make is less DRY ? How do I retrieve multiple url parameter ?
if(isset($_GET["cat"])) {
switch ($cat) {
case 'section1':
if(isset($_GET["language"])) {
$language = htmlspecialchars($_GET["language"]);
if($language == "de") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/dp/low/*.jpg');
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
elseif ($language == "en") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/ep/low/*.jpg');
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
elseif ($language == "cz") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/cp/low/*.jpg');
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
break;
case 'section2':
//the same like in section 1, path is .../section2/...
break;
case section3:
//the same like in section 1, path is .../section3/...
break;
default:
//the same like in section 1
break;
}
else {
//the same like in section 1
}
The path d=german, e=english, c=czech, p=prices, n=noprices
You could shorten/remove many if else statements with just doing the checks:
$lang_code = $language[0];
There you have your first letter, you can do the same with every GET parameter.
So you can use that as in:
$files=glob('pages/section1/'.$lang_code.'p/low/*.jpg');
You can do the same for everything else.
P.s.: don't forget to sanitze any user input i.e.:
$language=mysqli_real_escape_string($conn, $_GET['language']);
I'd probably do something like this:
<?php
$allowedCat = ['section1', 'section2'];
$allowedLanguage = ['pl', 'en', 'cz'];
$allowedPrice = ['pl', '??'];
$cat = (isset($_GET["cat"])) ? $_GET["cat"] : null;
$language = (isset($_GET["language"])) ? $_GET["language"] : null;
$prices = (isset($_GET["prices"])) ? $_GET["prices"] : null;
if (!in_array($cat, $allowedCat)) throw new \Exception('Invalid `cat`');
if (!in_array($language, $allowedLanguage)) throw new \Exception('Invalid `language` option.');
if (!in_array($prices, $allowedPrice)) throw new \Exception('Invalid `price` option.');
$someVar1 = ($prices === 'pl') ? 'p' : 'n';
$someVar2 = $language[0];
$files = glob("pages/{$cat}/{$someVar1}{$someVar2}/low/*.jpg");
Think that should be self explanatory. Translates one to one really. Was not certain on how the other price option was specified...

How i can use if/else/elseif statment in my case - PHP

How i can use if/else/elseif... in my case,
Because when i try those statment,
It says: syntax error, unexpected 'if' (T_IF)
I need to repeat elseif more than 1x time
$row = array();
$row[] = if($aRow['status'] == "deleted"){'code..'};
This might be what you are after. You would loop over each record in your result array you get from fetchAll(), put your if/elseif block here, then I'm assuming your doing some sort of processing and saving the value to $row array?
$row = array();
$result = $sth->fetchAll();
foreach($result as $aRow){
if($aRow['status'] == "deleted"){
//do something
$row[] = //whatever
}
elseif($aRow['status'] == "something else"){
//do something else;
$row[] = //whatever else
}
}
You have 2 ways for implementing this by PHP:
The 1st way
you can use if/else/elseif:
if ($status_var=="deleted")
{
//code .....
}
elseif ($status_var=="inserted")
{
//code .....
}
elseif ($status_var=="edited")
{
//code .....
}
esle
{
//code .....
}
The 2nd way
You can use switch/case structure:
switch ($status_var)
{
case "deleted":
//code .....
break;
case "inserted":
//code .....
break;
case "edited":
//code .....
break;
default:
//code .....
}
You can use ternary operator to assign the result:
$row = array();
$row[] = $aRow['status'] == "deleted" ? 'code..' : null;
When you need to do more things depending on status, best way would be to introduce a function for that:
function process($aRow) {
if ($aRow['status'] == "deleted") {
// do something when `deleted`
return 1;
} elseif ($aRow['status'] == "new") {
// do something when `new`
return 2;
} elseif ($aRow['status'] == "updated") {
// do something when `updated`
return 3;
} else {
// do something else
return 4;
}
}
$row = array();
$row[] = process($aRow);

If, elseif and else statements returning incorrect results

I am having some problem creating this fail catch in PHP. I want require 'error.php'; to be shown when a user enters a bad URL, which returns $echo_error_404 = 1.
I use normal PHP routing, which means, my URL gets split up into /example1/example2/example3/.
I have this page projects which is the same as $routes[1] when I enter that page. The file projects.php does not exist. Understood correctly projects should fall in under the second elseif statement. And then be given $error_echo_404 = 1 when file_exists() is used. However... for some weird reason it continues all the way into $echo_content = '<div id="content-wrap">'.$php_doc_html."</div>";
PS: Also I know a lot of my code is poorly formatted, however, I did it trying to solve my problem.
The code to check what files to require, and run error check:
// FIND WEBSITE CONTENT
$echo_content = "";
if(empty($routes[1])){
require 'frontpage.php';
if($echo_error_404 == 0){
$echo_content = '<div id="content-wrap">'.$front_page_html."</div>";
}
}
elseif((!empty($routes[1])) && ($routes[1] == "page")){
require 'frontpage.php';
if($echo_error_404 == 0){
$echo_content = '<div id="content-wrap">'.$front_page_html."</div>";
}
}
elseif((!empty($routes[1])) && ($routes[1] != "page")){
$php_doc = $routes[1];
$file_exist = $php_doc.".php";
if(file_exists($file_exist)){
require $php_doc.".php";
if($echo_error_404 == 0){
$echo_content = '<div id="content-wrap">'.$php_doc_html."</div>";
}
if(empty($echo_content)){
$echo_error_404 = 1;
}
}
else{
$echo_error_404 = 1;
}
}
else{
$echo_error_404 = 1;
This is how I run the correct version if $echo_error_404 = 1:
if($echo_error_404 == 1){
require 'error.php';
$error_index_head = <<< EOF
HTML TAG OPENING, TITLE, HEAD AND BODY OPENING ETC.
EOF;
echo $error_index_head;
echo $header_html;
echo '<div id="content-wrap">'.$error_page_html.'</div>';
echo $echo_index_after;
echo $footer_html;
}
else{
echo $echo_index_head;
echo $header_html;
echo $echo_content;
echo $echo_index_after;
echo $footer_html;
}
This is what I get in the browser as return, clearly showing that $echo_error_404 was not assigned the value 1:
var_dump() results:
elseif((!empty($routes[1])) && ($routes[1] != "page")){
$php_doc = $routes[1];
var_dump($php_doc);
$php_doc_html = "";
var_dump($php_doc_html);
// THE CODE INBETWEEN
else{
$echo_error_404 = 1;
}
var_dump($php_doc_html);
var_dump($echo_error_404);
Return shows that projects is in $routes[1] and that $echo_error_404 is = 1:
string(8) "projects"
string(0) ""
string(0) ""
int(1)
Might be a bit cleaner to use switch(). If we first check that $routes[1] is empty or not, we should not need to do it again in later conditions. It does not make sense to me that you then check it agian in your elseif. If it was empty, it would satisfy the first if and not move on to the next parts of the statement.
// Assume no content
$echo_content = "";
// Check for content
if(empty($routes[1])){
require 'frontpage.php';
if($echo_error_404 == 0){
$echo_content = '<div id="content-wrap">'.$front_page_html."</div>";
}
} else {
switch($routes[1]){
case "page":
require 'frontpage.php';
if($echo_error_404 == 0){
$echo_content = '<div id="content-wrap">'.$front_page_html."</div>";
}
break;
default:
$file_exist = "{$routes[1]}.php";
if(file_exists($file_exist)){
require $file_exist;
if($echo_error_404 == 0){
$echo_content = '<div id="content-wrap">'.$php_doc_html."</div>";
}
} else {
$echo_error_404 = 1;
}
}
}
if(empty($echo_content) || $echo_content == ""){
$echo_error_404 = 1;
}

My script doesn't work as expected

This is the button
<a href="index.php?p=contact">contact<a>
This is the php script:
<?php
$p = isset($_GET['p']);
if($p == "artist")
{
include 'artist.php';
}
if($p == "contact")
{
include 'contact.php';
}
if($p == "releases")
{
include 'releases.php';
}
if($p == "downloads")
{
include 'downloads.php';
}
else
{
include 'home.php';
}
?>
So my script should include contact.php when I hit the button, but instead of including only contact.php it includes all php files. (this happens also with the other buttons).
Right now your $p variable equals true (this is what isset returns).
Change $p = isset($_GET['p']); to $p = $_GET['p']; and you'll be good
Even better:
$p = isset($_GET['p']) ? $_GET['p'] : false;
in this case you're secured against p being null
EDIT:
There is also another issue with your code - last else statement. It is always true when $p is different than downloads. So either you change every if to else if like this:
if($p == 'artist')
{
include 'artist.php';
}
else if($p == 'contact')
{
include 'contact.php';
}
(...)
else
{
include 'home.php';
}
or change this to switch statement:
switch($p)
{
case 'artist':
include 'artist.php';
break;
(...)
default:
include 'home.php';
}
isset($_GET['p']) returns true or false, so the code comparing $p to some strings will always return true and run the code inside the if block.
Change $p = isset($_GET['p']) simply to $p = $_GET['p']
To make this (more) reusable, you should alter your script a bit. Create a simple whitelist, check it the parameter is allowed, and if yes, include the $_GET['p']'s value directly:
$allowed = false;
if (isset($_GET['p']))
{
switch $_GET['p'] {
case 'contact':
$allowed = true;
break;
case 'artist':
$allowed = true;
break;
// and so on for all your IFs
}
if ($allowed === true) {
include $_GET['p'].'.php'
}
else
{
die('illegal parameter found')
}
}

Optimising a PHP If/Else statement

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.

Categories