I have been trying to display a menu name from my CMS database that I created myself, I got it displayed perfectly but there is a really weird error, I spent many hours to discover the solution but I couldn't.
The problem is that I want to display the menu name as page H1 in line 50 exactly so whenever you click on the menu name its also displaying as H1 title.
The menu name is displaying correctly, but the sub menu(pages) displaying N instead of the page name, I don't know where is that N is coming from.
NOTE: There is no problem with the database connection or retrieving data.
This is my content page code:
<?php include("includes/header.php"); ?>
<?php require_once 'includes/db_connection.php'; ?>
<?php require_once 'includes/b_functions.php'; ?>
<?php require_once 'includes/cms_constants.php'; ?>
<?php db_connect();?>
<?php
if (isset ( $_GET ['subj'] )) {
$sel_subject = get_subject_by_id ( $_GET ['subj'] );
$sel_page = "NULL";
} elseif (isset ( $_GET ['pages'] )) {
$sel_subject = false;
$sel_page = get_page_by_id ( $_GET ['pages'] );
} else {
$sel_subject = "NULL";
$sel_page = "NULL";
}
?>
<table id="structure">
<tr>
<td id="navigation">
<ul class="subjects">
<?php
$subject_set = get_all_subjects();
while ($subject = mysql_fetch_array($subject_set)) {
echo "<li";
if ($subject["id"] == $sel_subject["id"]) { echo " class=\"selected\""; }
echo "><a href=\"contents.php?subj=" . urlencode($subject["id"]) .
"\">{$subject["menu_name"]}</a></li>";
$page_set = get_pages_for_subject($subject["id"]);
echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li";
if ($page["id"] == $sel_page["id"]) { echo " class=\"selected\""; }
echo "><a href=\"contents.php?pages=" . urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}
echo "</ul>";
}
?>
</ul>
</td>
<td id="page">
<?php if (!is_null($sel_subject)) { // subject selected ?>
<h2><?php echo $sel_subject['menu_name']; ?></h2>
<?php } elseif (!is_null($sel_page)) { // page selected ?>
<h2><?php echo $sel_page['menu_name']; ?></h2>
<div class="page-content">
<?php echo $sel_page['content']; ?>
</div>
<?php } else { // nothing selected ?>
<h2>Select a subject or page to edit</h2>
<?php } ?> </td>
</tr>
</table>
<?php require_once 'includes/footer.php';?>
Your 'N' is coming from the "NULL" string. I believe you meant to set your variables with actual NULL and not a string. Like:
$var = NULL;
As opposed to:
$var = "NULL";
When you access a variable that is set to "NULL" as an array, you will get the 'N' (as the string is treated as an array). For instance;
$var = "NULL";
echo $var[0]; // 'N'
Furthermore, if you test for NULL on a string it will return false (the variable is non-null);
$var = "NULL";
if($var) {
echo "var is: " . $var;
}
else {
echo "var is NULL!";
}
The above should output "var is: NULL".
I say this from experience (I did this when I started coding PHP). However, the root of your problem likely doesn't stop there as your variables should be set in subsequent conditionals. I would go through your while statements, and if statements and ensure your variables are being set appropriately. (var_dump($var) or print_r($var) through suspect blocks).
Related
Do variables in the for / foreach loop have a local scope? If so, how do I make it global?
page.php:
<?php
$title = "2";
$menu[0] = "1";
$menu[1] = "2";
$menu[2] = "3";
$menu[3] = "4";
$menu[4] = "5";
$menu[5] = "6";
$menu[6] = "7";
$menu[7] = "8";
foreach ($menu as $value){
if ($title == $value){
$active = "active";
echo "if " . $active. $title . $menu[$x] ." <br /><br />";
}
else {
$active = "";
echo "else " . $active. $title . $menu[$x] ." <br /><br />";
}}
include "header.php";
foreach ($menu as $value) {
var_dump($active);
echo "$value <br>";
}
include "header.php";
?>
<!-- begin page content -->
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<!-- end page content -->
<?php
include "footer.php";
?>
Essentially, I have this line in the header.php:
<li class="mainNav <?php echo $active; ?>" style="z-index:8">
<?php echo $menu[0]; ?></li>
I want the list to have class="mainNav active" if it's that page and class="mainNav" if not.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
So I created a function from #urfusion suggestion. Now page.php:
<?php
$title = "2";
$menu[0] = "1";
$menu[1] = "2";
$menu[2] = "3";
$menu[3] = "4";
$menu[4] = "5";
$menu[5] = "6";
$menu[6] = "7";
$menu[7] = "8;
?>
<?php
function mainNav($menu) {
foreach ($menu as $value){
if ($title == $value){
$active = "active";
echo "if " . $active. $title . $menu[$x] . " <br /><br />";
}
else {
$active = " ";
echo "else " . $active. $title . $menu[$x] . " <br /><br />";
}
echo "function" . $active . $value;
return $active;
}
}
include "header.php";
?>
<!-- begin page content -->
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<!-- end page content -->
<?php
include "footer.php";
?>
And the header.php:
<li class="mainNav <?php mainNav(); ?>" style="z-index:8">
<?php echo $menu[1]; ?></li>
Still nothing and now I seem to have lost the output of the echo statements ...
Do variables in the for / foreach loop have a local scope? If so, how do I make it global?
There are only two kinds of scopes in PHP: the global scope and local function scope.
A local function scope contains the function's parameters and the variables that are set inside the function body. The scope is created when the function is invoked and it is destroyed when the execution of the function completes.
The global scope contains all the variables that are set by the code outside any function. It is created when the main script (the one invoked by the interpreter) starts.
The included and required files do not create new scopes. The code that is outside functions in the included files runs in the scope where the include or require statement is placed. This means, global scope if the include statement appears outside any function of the local scope of the function that contains the include statement. All four include statements (include, include_once, require, require_once) work the same regarding this matter.
Any variable is available in its scope since it was set for the very first time until it is removed using unset() or until its scope is destroyed.
Read more about variables scope on the PHP documentation.
To answer your question: if the for or foreach loop is placed in a function then the variables they define have local scope (the scope of the function); otherwise they have global scope.
The problem in your code (the bad indentation doesn't help you see it) is in the first foreach.
This is the code properly indented:
foreach ($menu as $value) {
if ($title == $value) {
$active = "active";
echo "if " . $active. $title . $menu[$x] ." <br /><br />";
} else {
$active = "";
echo "else " . $active. $title . $menu[$x] ." <br /><br />";
}
}
The problem is obvious: it modifies the value of variable $active on each iteration. All but the last assignment of $active is useless. Only the last one counts. And, most probably, on the last iteration it takes the else branch of if ($title == $value) and $active becomes '' (the empty string).
There are several simple solutions for the problem. For example, you can display the menu inside the aforementioned foreach:
foreach ($menu as $value) {
if ($title == $value) {
$active = "active";
} else {
$active = "";
}
?>
<li class="mainNav <?php echo $active; ?>" style="z-index:8">
<?php echo $value; ?></li>
<?php
}
In fact, all this stuff should go into header.php.
your code should look like
$active = "";
foreach ($menu as $value){
if ($title == $value){
$active = "active";
echo "if " . $active. $title . $menu[$x] ." <br /><br />";
}
else {
$active = "";
echo "else " . $active. $title . $menu[$x] ." <br /><br />";
}
}
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
local
global
static
for more information on scope
I have some tabs. In that sometimes first tab is "introduction" and sometimes "outline" is first tab. I have set introduction class=active when it comes first. But when outline comes first I am not getting how to set its class as active.
code is like below
<ul class="nav-tabs" role="tablist">
<?php
$tabs = array();
if(!$sessId == "" && !$checkcourse){
$tabs = array("introduction"=>true, "outline"=>true,"announcement"=>false,"discussion"=>false,"review"=>true, "student"=>true, "comment"=>true);
} else if($sessId == "") {
$tabs = array("introduction"=>true, "outline"=>true,"announcement"=>false,"discussion"=>false,"review"=>true, "student"=>false, "comment"=>true);
} else {
$tabs = array("introduction"=>false, "outline"=>true,"announcement"=>true,"discussion"=>true,"review"=>true, "student"=>true, "comment"=>false);
}
?>
<?php if($tabs['introduction']) { ?>
<li class="active">Introduction</li>
<?php } ?>
<?php if($tabs['outline']) { ?>
<li>Outline</li>
<?php } ?>
<?php if($tabs['review']) { ?>
<li>Review</li>
<?php } ?>
<?php if($tabs['student']) { ?>
<li>Student</li>
<?php } ?>
<?php if($tabs['comment']) { ?>
<li>Comment</li>
<?php } ?>
<?php if($tabs['announcement']) { ?>
<li>Announcement</li>
<?php } ?>
<?php if($tabs['discussion']) { ?>
<li>Discussion</li>
<?php } ?>
</ul>
Simple check with ternary operator is:
<?php if($tabs['outline']) {?>
<li <?=$tabs['introduction']? '' : ' class="active"';?>>Outline</li>
<?php } ?>
So you check if $tabs['introduction'] isset then you don't need class="active", else - add this class.
Update:
But as first item of tab can change, I advise to create simple foreach:
$is_first = true;
foreach ($tabs as $tab_name => $value) {
if ($value) {
echo '<li' . ($is_first? ' class="active"' : '') . '>' . $tab_name . '</li>';
$is_first = false; // fix that we have first value here
}
}
Here your main problem is how to link href value and caption.
I'm using multiple if statements to check a containing div, and output an image based on the container name. The code was working fine until I add a final "else" or change the if's out to elseif and I can't figure out why that's happening. When I try to add the else or elseif, the entire page fails to load. Any idea why this is happening?
<?php
if($viewMore['container_type'] == 'Large IMG' || $viewMore['container_type'] == 'Gallery') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'large_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$large = 0; foreach ($photoArray as $photo => $upload): if (++$large == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach ?>
<?php } ?>
<?php
elseif($viewMore['container_type'] == 'Medium IMG') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'small_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$medium = 0; foreach ($photoArray as $photo => $upload): if (++$medium == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach; ?>
<?php } ?>
<?php else { ?> SOMETHING HERE <?php } ?>
EDIT:
Other notes
I've tried wrapping the break; in brackets because I thought that piece following the count might be messing with something. Also removing the counter altogether or adding a semi colon after the endforeach didn't help.
Whenever you close your PHP block, think about all the text/HTML outside it being put into PHP's echo function.
What gave me alarm bells was this part:
<?php } ?>
<?php else { ?> ...
What that translates into is:
if (...) {
} echo "[whitespace]"; else {
}
which clearly makes your else block unexpected.
You should not close the PHP block between your closing if and opening else, i.e. do this instead:
...
} else {
...
Are PHP scripts reads from top to bottom? like HTML? because in this code
<?php require_once("./includes/connection.php")?>
<?php require_once("./includes/functions.inc.php"); ?>
<?php
if(isset($_GET['subj']))
{
$sel_subj = get_subject_by_id($_GET['subj']);
$sel_page = NULL;
}else if(isset($_GET['page']))
{
$sel_subj = NULL;
$sel_page = get_page_by_id($_GET['page']);
}else
{
$sel_subj = NULL;
$sel_page = NULL;
}
?>
<?php include("includes/header.inc.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<ul class = "subjects">
<?php
$subject_set = get_all_subjects();
while($subject = mysql_fetch_array($subject_set))
{
echo "<li";
if($subject['id'] == $sel_subj['id']) {echo " class =\"selected\"";}
echo "><a href=\"content.php?subj=" . urlencode($subject["id"]) .
"\">{$subject["menu_name"]}</a></li>";
echo "<ul class = 'pages'>";
$page_set = get_pages_for_subject($subject['id']);
while($page = mysql_fetch_array($page_set))
{
echo "<li";
if($page['id'] == $sel_page['id']){echo " class = \"selected\"";}
echo"><a href=\"content.php?page=" . urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}
echo "</ul>";
}
?>
</ul>
</td>
<td id="page">
<?php if(isset($sel_subj)){?>
<h2><?php echo "{$sel_subj['menu_name']}";?></h2>
<?php } ?>
<?php if(isset($sel_page)){?>
<h2><?php echo "{$sel_page['menu_name']}"?> </h2>
<?php }?>
</td>
</tr>
</table>
<?php require("includes/footer.inc.php"); ?>
specifically this part
if(isset($_GET['subj']))
{
$sel_subj = get_subject_by_id($_GET['subj']);
$sel_page = NULL;
}else if(isset($_GET['page']))
{
$sel_subj = NULL;
$sel_page = get_page_by_id($_GET['page']);
}else
{
$sel_subj = NULL;
$sel_page = NULL;
}
How is this if-else block being called if it's on top of the page?
It is run top-to-bottom one time per page view. On the initial view, assuming the URL has no parameters, then neither $_GET['subj'] or $_GET['page'] will be set.
If the link pointing back to the same page is clicked, then the entire PHP file will be reprocessed. If that link contained subj or page in the URL as a query variable, then the corresponding if block will be executed and the page will be altered accordingly.
Think of the PHP server as dynamically creating some HTML file that is sent to the web browser. Once it is sent, the server is done, and the PHP code is "gone." The only way to run more PHP code is to request a new page, where the process starts over.
(Even AJAX follows the same principles, although generally then you are dealing with partial data requests as opposed to full page views.)
Yes, scripts are run from top to bottom. I don't understand why you think that if-else block is any different? Those if clauses are run to set the $sel_subj and $sel_page variables before the rest of the page is executed and output.
PHP scripts are executed from top-to-bottom. What exactly is your problem?
How can I write the following statement in PHP:
If body ID = "home" then insert some html, e.g.
<h1>I am home!</h1>
Otherwise, insert this html:
<p>I'm not home.</p>
Doing it with native PHP templating:
<?php if ($bodyID==='home') { ?>
<h1>I am home!</h1>
<?php } else { ?>
<p>I'm not home!</p>
<?php } ?>
You can try using this :
$html = '';
if ( $body_id === 'home' )
{
$html .= '<h1>I am home!</h1>';
}
else
{
$html .= '<p>I\'m not home.</p>';
}
echo $html;
This will echo the html code depending on the $body_id variable and what it contains.
You can use a switch command like so:
switch($body)
{
case 'home': //$body == 'home' ?
echo '<h1>I am home!</h1>';
break;
case 'not_home':
default:
echo '<p>I'm not home.</p>';
break;
}
The default means that if $body does not match any case values, then that will be used, the default is optional.
Another way is as you say, if/else statements, but if within template / view pages you should try and use like so:
<?php if ($body == 'home'):?>
<h1>I am home!</h1>
<?php else:?>
<p>I'm not home!</p>
<?php endif; ?>
Assuming $bodyID is a variable:
<?php
if ($bodyID==='home') {
echo "<h1>I am home!</h1>";}
else {
echo "<p>I'm not home!</p>";}
?>
Personally I think that the best way to do that without refreshing and without having to set a variable (like $body or something like that) is to use a javascript code, this because "communications" between JS & PHP is a one-way communication.
<script language="javascript">
<!--
if( document.body.id === "home" ){
window.document.write("<h1>I am home!</h1>") ;
}
else{
window.document.write("<p>I'm not home!</p>") ;
}
-->
</script>
otherwise you can build a form and then take the body.id value using $_GET function... It always depends on what you've to do after you now body.id value.
Hope this will be usefull & clear.
you can try in the following way:
$body_id = "home";
if ($body_id == "home") {
echo "I am home!";
} else {
echo "I am not home!";
}
or
$body_id = "home";
if (strcmp($body_id, "home") !== 0) {
echo 'I am not home!';
}
else {
echo 'I am home!';
}
Reference:
https://www.geeksforgeeks.org/string-comparison-using-vs-strcmp-in-php/