Include PHP within a variable? - php

Say I have
$output = '';
and I want to include the following code within the double ''.
<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
<a href="?route=common/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
<a href="?route=subscribers/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
How could I go about doing this?

You could use output buffering, something like this:
<?php ob_start();?>
<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
<a href="?route=common/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
<a href="?route=subscribers/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
<?php
$output = ob_get_contents();
ob_end_clean();
?>
See In Action
Using this method of starting a buffer and then assigning the result to a variable is very handy and is used in some MVC frameworks.
Simple example:
<?php
/* Assign an array of values that will be passed
* to the loader then extracted into local variables */
$data['logged']=true;
$output = loadContentView('top_nav', $data);
function loadContentView($view, $data=null){
$path = SITE_ROOT.'/path/to/views/'.$view.'.php';
if (file_exists($path) === false){
return('<span style="color:red">Content view not found: '.$path.'</span>');
}
/* Extract $data passed to this function */
if($data != null){
extract($data);
}
ob_start();
require($path);
$return = ob_get_contents();
ob_end_clean();
return $return;
}
?>

I just changed my code to this instead... much easier
Thanks everyone for all the help!
<?php
if (!$this->customer->isLogged()) {
$output = '<ul class="nav megamenu"><li class="home"><span class="menu-title">Home</span></li>';
}else{
$output = '<ul class="nav megamenu"><li class="home"><span class="menu-title">Home</span></li>';
}
?>

Related

My route somehow keep redirecting to wrong url

so
i try make a pos(point of sale) program using ci3
im trying add a feature where admin can make new menu and submenu
but something went wrong
when i goto controller "sistem"
my route show "sitename/sistem/sistem/menu" this route supposed to "sitename/sistem/menu". another controller also effected when i goto "dashboard" controller the route show
"sistem/dashboard"
this is sistem controller
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Sistem extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('M_menu');
$this->load->model('M_user');
if (!$this->session->userdata('email')) {
redirect('auth');
}
}
public function index()
{
$this->menu();
}
public function menu()
{
$data['judulpage'] = 'Manajemen Menu';
$data['datamenu'] = $this->M_menu->getmenus()->result_array();
$data['user'] = $this->M_user->getuserdata()->row_array();
$this->form_validation->set_rules('menutambah', 'Menu', 'required');
// $this->form_validation->set_message([
// 'required' => 'Field menu add harus diisi'
// ]);
if ($this->form_validation->run() == false) {
$this->load->view('template/header', $data);
$this->load->view('template/sidebar', $data);
$this->load->view('sistem/menu', $data);
$this->load->view('template/footer');
} else {
$menu['menu'] = $this->input->post('menutambah');
$this->M_menu->insertmenu($menu);
$this->session->set_flashdata('flash','Sukses');
redirect('sistem');
}
}
this is the sidebar.php i think this is the problem but i cant find the solution
<?php
$role_id = $this->session->userdata('role_id');
$queryMenu = "SELECT `user_menu`.`id`, `menu`, `icon_menu`
FROM `user_menu`
JOIN `user_access_menu` ON `user_menu`.`id` = `user_access_menu`.`menu_id`
WHERE `user_access_menu`.`role_id` = $role_id";
$menus = $this->db->query($queryMenu)->result_array();
?>
<!-- BEGIN: Main Menu-->
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow" data-scroll-to-active="true">
<div class="main-menu-content">
<ul class="navigation navigation-main" id="main-menu-navigation" data-menu="menu-navigation">
<li class=" navigation-header"><span>MENU</span><i class=" feather icon-minus" data-toggle="tooltip" data-placement="right" data-original-title="Apps"></i>
</li>
<?php foreach($menus as $menu) : ?>
<?php
$menuid = $menu['id'];
$querysubmenu = "SELECT * FROM `user_sub_menu` WHERE `menu_id` = $menuid AND `is_active` = 1";
$submenus = $this->db->query($querysubmenu)->result_array();
?>
<li class=" nav-item"><i class="<?php echo $menu['icon_menu']; ?>"></i><span class="menu-title"><?php echo strtoupper($menu['menu']); ?></span>
<ul class="menu-content">
<?php foreach($submenus as $submenu) : ?>
<li>
<a class="menu-item" href="<?php echo $submenu['url']; ?>"><i class="<?php echo $submenu['icon']; ?>"></i><span><?php echo $submenu['title']; ?></span></a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
i take the url from database.
u can see from inspect mode, the href redirecting to sistem/menu which is coorect url but when i click it, it goto sistem/sistem/menu
You do not need to call double <?php ?> tag.
just do this
<?php echo base_url($submenu['url']); ?>
or simplify the echo syntax with
<?= base_url($submenu['url']); ?>
fixed href="<?php echo base_url(); ?> i add / this before php tag but somehow it worked but still directing to wrong url localhost/sistem/menu it supposed to localhost/site/sistem/menu, so i add base_url to add my sitename and it work, thx
<li>
<a class="menu-item" href="<?php echo base_url(); ?><?php echo $submenu['url']; ?>">
<i class="<?php echo $submenu['icon']; ?>"></i><span><?php echo $submenu['title']; ?></span></a>
</li>

fetching data from database - php codeigniter

I want to fetch some data (student details) from database but my code is not working.
This is my Controller
public function Student_Detail()
{
$student_id = $this->uri->segment(3);
$record = $this->WebAdmin_Model->Student_Details($student_id);
$this->load->view('admin/template/header.php');
$this->load->view('admin/students/student_details', $record);
$this->load->view('admin/template/footer.php');
}
This is my Model
public function Student_Details($student_id)
{
$query = $this->db->query("SELECT s.`student_id`,
s.`std_email`,
s.`std_fname`,
s.`std_lname`
FROM `student_main` AS s
WHERE s.`student_id` = $student_id");
return $query->result();
}
This is my View
<section class="panel">
<div class="user-heading">
<img src="<?=base_url();?>images/profile-avatar.jpg" alt="">
</div>
<ul class="nav nav-pills nav-stacked">
<li> <?php echo $record->std_fname; ?></li>
<li> <?php echo $record->std_lname; ?></li>
<li> <?php echo $record->std_email; ?></li>
</ul>
</section>
Note that there is not problem with the query. I want to know how to fetch student details. It gives me the following error. Message : Undefined variable: record
Try this:
In your controller:
$data['record'] = $this->WebAdmin_Model->Student_Details($student_id);
$this->load->view('admin/students/student_details', $data);
And in your view:
<ul class="nav nav-pills nav-stacked">
<?php
foreach($record->$row){
?>
<li> <?php echo $row->std_fname; ?></li>
<li> <?php echo $row->std_lname; ?></li>
<li> <?php echo $row->std_email; ?></li>
<?php
}
?>
</ul>
You need to pass your model data into record array then pass into view
Controller
$student_id = $this->uri->segment(3);
$record['data'] = $this->WebAdmin_Model->Student_Details($student_id);// store data into record array
$this->load->view('admin/template/header.php');
$this->load->view('admin/students/student_details', $record);
$this->load->view('admin/template/footer.php');
Use foreach loop to retrieve data
Views
<?php
foreach($data as $record)// use foreach loop
{ ?>
<li> <?php echo $record->std_fname; ?></li>
<li> <?php echo $record->std_lname; ?></li>
<li> <?php echo $record->std_email; ?></li>
<?php } ?>
You need to do it like this, because codeigniter try to extract variable from $record and it fails. So to make possible, make it,
$record['record'] = $this->WebAdmin_Model->Student_Details($student_id);
and then in your view,
<ul class="nav nav-pills nav-stacked">
<li> <?php echo $record->std_fname; ?></li>
<li> <?php echo $record->std_lname; ?></li>
<li> <?php echo $record->std_email; ?></li>
</ul>
Because codeigniter will extract variable from $record array

creating class active dynamically in php

I am creating a menu dynamically based on the categories registered on the dataBase, What I need is:
When someone click in the link, this option should have the css class 'active', showing in with page the user is and even the pages are created dynamically.
I have no idea how to do this because I am php student and I couldn't find this information in google for "Dynamically menus" Thank you very much.
<nav class="menu">
<ul class="list">
<li class="line"><a id="item" href="index.php">Home</a></li>
<?php
$categories = $db->select("select * from tbl_category");
if($categories){
while ($result = $categories->fetch_assoc()){
echo <<<HTML
<li id="line" ><a class="item" href="categories.php?category=$result[id]">$result[name]</a></li>
HTML;
}
}
?>
</ul>
<nav>
First of all, you're looping through that while loop and adding the id of "line" to each and every <li> element. I suggest you create unique id's for each list item. I don't necessary advocate using the code the way you have it, just as an example, here's your code edited to do just that:
if($categories){
$i = 1;
while ($result = $categories->fetch_assoc()){
$i++;
echo <<<HTML
<li id="line$i" ><a class="item" href="categories.php?category=$result[id]">$result[name]</a></li>
HTML;
}
}
Then when someone clicks on your link, just use jQuery with something like this:
$(".item").click(function() {
$(this).parent('li').addClass('active');
});
Try something like that:
<nav class="menu">
<ul class="list">
<li class="line"><a id="item" href="index.php">Home</a></li>
<?php
$current_page = isset($_GET['category']) ? $_GET['category']: -1;
$categories = $db->select("select * from tbl_category");
if($categories){
while ($result = $categories->fetch_assoc()){
echo '<li id="line">';
if($result['category'] === $current_page) {
// If we're currently in the active page then add the active class to the <a>
echo '<a class="item active" href="categories.php?category='. $result[id] .'">';
} else {
echo '<a class="item" href="categories.php?category='. $result[id] .'">';
}
echo $result['name'];
echo '</a>';
echo '</li>';
}
}
?>
</ul>
<nav>
Thank you all for help, based on your code, I solved doing this:
menu.php:
<nav class="menu" id="menu">
<ul id="list" class="list">
<li id="line" class="<?php if($presentPage == '0')echo 'active';?>"><a id="item" class="item" href="index.php">Home</a></li>
<?php
function checked($pp, $id){
if($pp == $id){
$status = 'active';
return $status;
}
}
$query = "select * from tbl_category";
$category = $db->select($query);
if($category){
while ($result = $category->fetch_assoc()){
echo "
<li id='line' class='".checked($presentPage, $result['id'])."'><a id='item' class='item' href='categories.php?category=".$result['id']."'>".$result['name']."</a></li>
";//end echo
}//end while
}//end if
?>
</ul>
</nav>
In my index.php:
<?php $presentPage = 0;?>
<?php require_once 'header.php';?>
<?php require_once 'menu.php';?>
and in my categories.php:
<?php
if (!isset($_GET['category']) || $_GET['category'] == NULL) {
$presentPage = 0;
}else{
$presentPage = intval($_GET['category']);//just to make sure that the variable is a number
}
?>
<?php require_once 'header.php';?>
<?php require_once 'menu.php';?>
///...my code...
and in my CSS of course:
.active{
background: linear-gradient(#821e82, #be5abe);
}
Thats is working perfectly for me, Thank for all help.

Build dynamic Mega Menu using recursion?

I'm trying to create a Mega Menu using PHP and I'm having a problem getting the structure to output correctly. I've hard-coded the Mega Menu to test everything and it works fine, but obviously I need PHP to create it for me.
I have an example with the Mega Menu hard-coded so everyone can see what I'm trying to create:
http://www.libertyeaglearms.com/dev
Or here's the code:
DESIRED OUTPUT:
<div id="wrapper">
<ul class="mega-menu">
<li class="mega-menu-drop">
Firearms
<div class="mega-menu-content">
<div class="column">
<h4>Rifles</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
<div class="column">
<h4>Handguns</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
<div class="column">
<h4>Shotguns</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
</div>
</li>
<li class="mega-menu-drop">
Archery
<div class="mega-menu-content">
<div class="column">
<h4>Bows</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
<div class="column">
<h4>Arrows</h4>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
CURRENT OUTPUT: (very messed up. be warned, lol)
<div id="wrapper">
<ul class="mega-menu">
<li class="mega-menu-drop">
archery
<div class="mega-menu-content">
<div class="column">
<h4>compound</h4>
<ul>
<h4>bows</h4>
<ul>
</div>
</li>
<li class="mega-menu-drop">
firearms
<div class="mega-menu-content">
<div class="column">
<h4>rifle ammunition</h4>
<ul>
<h4>ammunition</h4>
<ul>
</div>
</li>
</ul>
</div>
HERE MY PHP:
$json = json_decode($category->buildDepartments(NULL),true);
function buildDepartments($array,$parent)
{
$html = '';
foreach($array as $category)
{
if($category['parent'] == $parent)
{
if($category['parent'] == NULL)
{
$html .= '<li class="mega-menu-drop">' . "\n\t\t\t\t";
$html .= ''.$category['category_name'].'' . "\n\t\t\t\t";
$html .= '<div class="mega-menu-content">' . "\n\t\t\t\t\t";
$html .= '<div class="column">' . "\n\t\t\t\t\t\t";
$html .= buildDepartments($array,$category['category_id']);
$html .= '</div>' . "\n\t\t\t";
$html .= '</li>' . "\n\t\t\t";
}
else
{
$html .= buildDepartments($array,$category['category_id']);
$html .= '<h4>'.$category['category_name'].'</h4>' . "\n\t\t\t\t\t\t";
$html .= '<ul>' . "\n\t\t\t\t";
}
}
}
return $html;
}
print(buildDepartments($json,NULL));
HERE'S MY DATABSE:
EDIT AFTER BOUNTY
Building off what icktoofay suggested, I cannot seem to figure out the foreach() loops. The problem I'm getting is I get the department name inside the mega menu when I should see category and sub categories. I think the problem is I need to perform a loop with a specific parent id in order to get all the children, but I'm not really sure if that's the problem. Here's the code:
<div id="wrapper">
<ul class="mega-menu">
<?php $json = json_decode($category->buildDepartments(NULL)); ?>
<?php foreach($json as $category): ?>
<li class="mega-menu-drop">
<?php if($category->parent === NULL){echo $category->category_name;} ?>
<div class="mega-menu-content">
<?php foreach($category as $subcategory): ?>
<div class="column">
<?php if($category->category_id === $category->parent){echo '<h4>' . $category->category_name . '</h4>';}?>
<ul>
<?php foreach($category as $subcategory)
{
echo '<li>' . $category->category_name . '</li>';
}
?>
</ul>
</div>
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
Since it's a fixed depth and the format for each level is different, recursion may not be appropriate. Additionally, putting everything in strings is inelegant. Instead, you may want to try weaving the HTML and loops together like this:
<div id="wrapper">
<ul class="mega-menu">
<?php foreach($categories as $category): ?>
<li class="mega-menu-drop">
<?php echo $category->name; ?>
<div class="mega-menu-content">
<?php foreach($category->subcategories as $subcategory): ?>
<!-- and so on -->
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
The code I've used here assumes you've already got it from a sort-of-flat-array to a tree-like structure. For example, if we've got a Category class:
class Category {
public $id;
public $parentID;
public $name;
public $parent;
public $subcategories;
public function __construct($id, $parentID, $name) {
$this->id = $id;
$this->parentID = $parentID;
$this->name = $name;
$this->parent = null; // will be filled in later
$this->subcategories = array(); // will be filled in later
}
}
And an array of associative arrays like you might get from a database call (which we'll call $flatCategories), we can build a bunch of not-yet-connected Category instances like this:
$categories = array();
foreach($flatCategories as $flatCategory) {
$categories[$flatCategory['id']] =
new Category($flatCategory['category_id'],
$flatCategory['parent'],
$flatCategory['category_name']);
}
Then we can connect them all up into a hierarchal structure:
foreach($categories as $category) {
if($category->parentID !== null) {
$category->parent = $categories[$category->parentID];
$category->parent->subcategories[] = $category;
}
}
Now they're all linked up and we only care about keeping references to the roots:
$roots = array();
// This could, of course, be merged into the last loop,
// but I didn't for clarity.
foreach($categories as $category) {
if($category->parentID === null) {
$roots[] = $category;
}
}
Now $roots contains all the root categories, and it's fairly simple to traverse. In my example at the top, I was assuming $categories had something similar to $roots in it.
you need to generate something called a super tree and use a recursive function to echo out each branch, this will allow for an unlimited depth tree, but, it also allows for an unknown depth tree.
First, SQL:
SELECT category_id, parent, category_name
Second, use SQL to create tree:
$super_tree = array();
while(($row = mysql_fetch_assoc($res)) != NULL) {
$parent = $row['parent'] == NULL ? 0 : $row['parent']; //clean up the parent
$super_tree[$parent][$row['category_id']] = $row['category_name'];
}
Third, echo out the tree
function echo_branch($tree_branch, $tree_root) {
echo("<ul>\n"); //open up our list for this branch
foreach($tree_branch as $id => $name) { //foreach leaf on the branch
echo("<li>"); //create a list item
echo("{$name}"); //echo out our link
if(!empty($tree_root[$id])) { //if our branch has any sub branches, echo those now
echo_branch($tree_root[$id], $tree_root); //pass the new branch, plus the root
}
echo("</li>\n"); //close off this item
}
echo("</ul>\n"); //close off this list
}
echo_branch($super_tree[0], $super_tree); //echo out unlimited depth tree structure
this allows for unlimited depth in your tree structure and allows for simple code to be able to create the structure within the code base.
All that you would need to do now is add in your extra's such as classes and your extra html elements in the correct places.
if you are looking to track the current depth of the tree to be able to echo different things depending on the depth, you can make the following alterations
In the function definition
function echo_branch($tree_branch, $tree_root, $depth) {
In the recursive call within the if
echo_branch($tree_root[$id], $tree_root, $depth++);
In the initial call
echo_branch($super_tree[0], $super_tree, 0);
Look like you are using the variable
$category
when you should use
$subcategory
Try this:
<div id="wrapper">
<ul class="mega-menu">
<?php $json = json_decode($category->buildDepartments(NULL)); ?>
<?php foreach($json as $category): ?>
<li class="mega-menu-drop">
<?php if($category->parent === NULL){echo $category->category_name;} ?>
<div class="mega-menu-content">
<?php foreach($category as $subcategory): ?>
<div class="column">
<?php if($subcategory->category_id === $category->parent){echo '<h4>' . $category->category_name . '</h4>';}?>
<ul>
<?php foreach($subcategory as $subcategory2)
{
echo '<li>' . $subcategory2->category_name . '</li>';
}
?>
</ul>
</div>
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>

Validate echo PHP

Im trying to validate my output data from a php site that Im calling with
<?php include_once('nav.inc.php');
?>
The thing is when Im using this code
<ul>
<li>GÄSTBOK</li>
<li>OM MIG</li>
<li>PORTFOLIO</li>
<li>CURRICULUM VITAE</li>
</ul>
I wont get any errors, But when Im trying with the other code I get alot of errors. Is there any way to write the code so It validates ?
This is the code thas bugging me
<?php
$index = 'menu';
$gb = 'menu';
$portfolio = 'menu';
$cv = 'menu';
$menuLinkid=basename($_SERVER['PHP_SELF'],'.php');
if($menuLinkid=='index'){
$index = 'myButtons';
}else if($menuLinkid=='gb'){
$gb ='myButtons';
}else if($menuLinkid=='portfolio'){
$portfolio ='myButtons';
}else if($menuLinkid=='cv'){
$cv ='myButtons';
}
?>
<div id="fronticon">
<a href="contact.php"><img src="images/em.png" alt="Email" title="Email"/>
</a>
</div>
<ul>
<li><a class="<?php echo $index; ?> "href="index.php">OM MIG</a></li>
<li><a class="<?php echo $gb; ?> "href="gb.php">GÄSTBOK</a></li>
<li><a class="<?php echo $portfolio;?> " href="portfolio.php">PORTFOLIO</a></li>
<li><a class="<?php echo $cv; ?> "href="cv.php">CURRICULUM VITAE</a></li>
</ul>
Thanks
You need spaces between the ?> " and the href. You can't have them next to each other with no space.
Should be:
<li><a class="<?php echo $index; ?> " href="index.php">OM MIG</a></li>

Categories