using if else with codeigniter return value - php

I am using codeigniter framework for one of my inventory management systems.
I prefer using php due to its variable functionality which makes things easier.
So I am trying to get the username from session and then check the database for the level of the user and accordingly he should be able to view links in the navigation menu.
$this->db->select('level');
$this->db->where('name', $this->session->userdata('name'));
$query = $this->db->get('admin');
if ($query) {
foreach ($query->result() as $row)
{
echo $row->level ;
}
}
This works fine and gets the level of the logged in user.
Now I want to use a if condition with this value, so I am using this -
if ($this->$row->level = '3') {
?>
<li class="">
Employee Sales Report
</li>
<?php } ?>
But nothing seems to happen here, No error or any notice.
I have no clue what I am doing wrong here.

if ($this->$row->level = '3') {
?>
<li class="">
Employee Sales Report
</li>
<?php } ?>
you shouldn't use = operation for equal. should use == or === for equal. by that code you put 3 $this->$row->level and make it's value 3.
if ($this->$row->level == '3') {
?>
<li class="">
Employee Sales Report
</li>
<?php } ?>

Related

If field == null display else don't

My recordset is:
mysqli_select_db($KCC, $database_KCC);
$query_rsOtherServices = "SELECT pagecontent.mainMenuID, mainmenu.mainMenuLabel, pagecontent.subMenuID, submenu.subMenuLabel, pagecontent.contentID, pagecontent.contentTitle FROM submenu RIGHT JOIN (mainmenu RIGHT JOIN pagecontent ON mainmenu.mainMenuID = pagecontent.mainMenuID) ON submenu.subMenuID = pagecontent.subMenuID WHERE pagecontent.mainMenuID = 1 AND pagecontent.subMenuID IS NULL";
$rsOtherServices = mysqli_query($KCC, $query_rsOtherServices) or die(mysqli_error());
$row_rsOtherServices = mysqli_fetch_assoc($rsOtherServices);
$totalRows_rsOtherServices = mysqli_num_rows($rsOtherServices);
and the code I'm using to display the record is:
<?php do { ?>
<li><h4><?php echo $row_rsOtherServices['contentTitle']; ?></h4></li>
<?php } while ($row_rsOtherServices = mysqli_fetch_assoc($rsOtherServices)); ?>
This all works fine if a record exists but if there is no record, a 'link' is available to click even though it's not visible.
I have tried <?php if ($totalRows_rsOtherServices['subMenuID'] === Null) { ?>, <?php if ($totalRows_rsOtherServices['subMenuID'] > 0) { ?>, <?php if ($totalRows_rsOtherServices['subMenuID'] == true) { ?>, <?php if ($totalRows_rsOtherServices['subMenuID'] == false) { ?>but to no avail.
I know nothing about programming and even less about PHP so I'm not even sure is I'm going in the right direction.
I need to get rid of the 'invisible link'.
Because you are using do ... while, use while only.
Try
<?php while (($row = mysqli_fetch_assoc($rsOtherServices))) { ?>
<li>
<a href="familyservices.php?idVal=<?php echo $row['contentID']; ?>">
<h4><?php echo $row['contentTitle']; ?></h4>
</a>
</li>
<? } ?>
OK, I've figured it out.
Instead of using $((totalRows_rsOtherServices['subMenuID']) > 0), I changed it to (($row_rsOtherServices) > 0). This did the trick.
However, if I use the while (($row = mysqli_fetch_assoc($rsOtherServices)))... as suggested, even if there is a record, it doesn't display.
At this moment in time I'm not going to worry to much about that but will investigate it in the future.

Paginating MySql Results

I have a table that pulls tickets from a MYSQL database and displays them to the user. This part works wonderfully! But, once the user gets 5-10 tickets, the page becomes long and ugly. I am wanting to paginate the responses automatically to show maybe 5 tickets per page and show the rest on following pages.
I am using Bootstrap and have the following for the display of the pagination. "Although I fear this is only pseudo code" I added id's to each main element.
<ul class="pager" id="pagerUL">
<li class="previous" id="previousUL">
← Previous
</li>
<li class="next" id="nextUL">
Next →
</li>
</ul>
Essentially the only code used to pull the database information on the page is:
<?php if(count($tickets) > 0) : ?>
<?php foreach ($tickets as $ticket): ?>
//table content
<?php endforeach ?>
<?php else : ?>
<tr>
<td colspan="7">No Tickets Created.</td>
</tr>
<?php endif; ?>
I thought we could add something to the <?php if(count($tickets) > 0) : ?> But honestly, I am not sure as I am not a expert at php and never even attempted or had the need to build pagination up until now. Any help, guidance, thoughts would be appreciated.
Pass the page number thru the URL and then grab it via php with $_GET.
$page = $_GET['page'];
$per_page = 10; // Define it as you please
$start = $page*$per_page;
$query = "SELECT * FROM table LIMIT ".$start.", ".$per_page;
$result = mysql_query($query);
$count = mysql_num_rows($result);
$i = 0;
for($i=0;$i<$count;$i++)
{
//echo out what you want
echo "";
}
$total_pages = ceil($count/$per_page);
for($i=0;$i<$total_pages;$i++)
{
if($page != $i)
{
echo "<a href='/page.php?page=".$i."'>".$i."</a>";
} else
{
echo $i;
}
}

Removing Duplicate Entries from Join

I am running into a problem that I feel like is somewhat simple in principle, so I may not be going about this the correct way. I essentially am listing "events" on a page that have their own respective "comments". I am joining to two tables and hoping to run a foreach loop to get all of the events along with their comments. Unfortunately, if an event has more than one comment it's reprinting the original event because of the join (i suspect). What is a better way to achieve what I am trying to accomplish?
In my model:
function get_events()
{
$this->db->select('*');
$this->db->from('events');
$this->db->join('comments', 'comments.event_id = events.id', 'left');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
}
And in the view:
<?php foreach($events as $row): ?>
<div class="event">
<?= $row->event; ?>
<?php if($row->comment == null): ?><br>
<i>No comments.</i>
<?php else: ?>
<div class="comment">
<?= $row->comment; ?>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
In the db I basically have 3 events, one with 2 comments, one with just 1, and one with zero comments. The first event prints twice, each with a different comment, the second event prints fine with its own comment and the third one works perfectly, printing "no comments" since there is nothing joined with it.
Hopefully this all makes sense!
MT
You can check wether you already echoed the event:
<?php
$lastEvent = null;
foreach($events as $row) {
if($row->event != $lastEvent) {
echo '<div class="event">' . $row->event;
}
if($row->comment == null) {
echo '<br><i>No comments.</i>';
} else {
echo '<div class="comment">' . $row->comment . '</div>';
}
if($row->event != $lastEvent) {
echo '</div>';
}
$lastEvent = $row->event;
}

CodeIgniter retrieve specific data from the controller within a view

So basically what I am trying to do is retrieving a list of categories from the database and placing it in a variable called $data['categories'].
In the view I am listing this up by simply using a foreach() statement. So far so good.
Though, some categories have subcategories (not all of them). Now, I added a row in the database saying 'is_direct' (has subcategories or not) which displays whether the category has subcategories or not.
Now, I want to list up those subcategories in case they exist.
Here the method to display the header (where the categories and subcategories will be listed) (Don't mind the private, it should be that).
private function show_header($template='default',$page_name='default')
{
// Get the categories.
$data['categories'] = $this->CI->ws_category->get_categories();
// Display the header.
$this->CI->load->view("templates/".$template."/template/header",$data);
}
This method calls for the method get_categories(), that's the one below (simple Active Record).
public function get_categories()
{
// Prepare the SQL query.
$this->db->select('*');
$this->db->from(APP_PREFIX.'categories');
$this->db->order_by('name_clean');
// Execute the query.
$query = $this->db->get();
// Get the results from the query.
$result = $query->result_array();
// Return the array with data.
return $result;
}
And below the view, you can see where the submenu would go.
<?php
// Loop through all the categories.
foreach ($categories as $item):
?>
<li class='nav_link <?php ($item['is_direct'] == '1' ? 'nav_subcats' : ''); ?>'>
<a href='<?php echo base_url().'category/'.$item['category_id'].'-'.$item['name_clean'].'.html';?>' class='nav_main_link'><?php echo $item['name']; ?></a>
<?php
// In case subcategories are present.
if ($item['is_direct'] != '1')
{
?>
<div class='nav_submenu'>
<ul>
<li><a href='#' class='nav_sub_link'>submenu item</a></li>
</ul>
</div>
<?php
}
?>
</li>
<?php
// End the loop.
endforeach;
?>
Can somebody help me?
Thank you.
The approach I would take would be to build out more complete data in your model (or controller) so that you can simply loop through it in the view (like you are currently doing). Below I have written a possible solution. I have modified your get_categories() method to query for subcategories as well. Then, in the view, we check to see if a category has any subcategories and outputs them as necessary.
public function get_categories_and_subcategories()
{
// Prepare the SQL query.
$this->db->select('*');
$this->db->from(APP_PREFIX.'categories');
$this->db->order_by('name_clean');
// Execute the query.
$query = $this->db->get();
// Get the results from the query.
$result = $query->result_array();
// Get subcategories
for ($i = 0; $i < count($result); $i++) {
// Check if subcategory
if ($result[$i]['is_direct']) {
// Query for subcategories - made up for demonstrational purposes
$query = $this->db->query("SELECT * FROM subcategories WHERE parent_id='".$result[$i]['id']."'");
// Add subcategories to category item
$result[$i]['subcategories'] = $query->result_array();
} else {
$result[$i]['subcategories'] = array();
}
}
// Return the array with data.
return $result;
}
Then in the view:
<li class='nav_link <?php ($item['is_direct'] == '1' ? 'nav_subcats' : ''); ?>'>
<a href='<?php echo base_url().'category/'.$item['category_id'].' '.$item['name_clean'].'.html';?>' class='nav_main_link'><?php echo $item['name']; ?></a>
<?php if (count($item['subcategories']) > 0): ?>
<div class='nav_submenu'>
<ul>
<foreach ($item['subcategories'] as $subcategory): ?>
<li><a href='<?php echo $subcategory['url']; ?>' class='nav_sub_link'><?php echo $subcategory['name']; ?></a></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
</li>
Keep in mind I haven't tested this code but you should be able to adopt the general idea to your application.

How to fill HTML list using data from a MySQL database?

I have an html webpage, and it contains a unordered list .So i want to fill this list using items that are stored in a MySQL database, an example item is provided to be clear.
<ul class="content">
<li class="class1">
<p id="id1">paragraph1</p>
<div class="class1sub">
<p>paragraph1sub</p>
</div>
</li>
So i want to retrieve the whole list items from the database and display it on the webpage. The problem is that each list item is stored in the database besides its CSS classes and IDs to be styled. Here is an example of a couple of items:
liclass - id - paragraph1 - divclass - paragraph2
So I'm thinking of maybe using JavaScript/PHP and MySQL ... but no starting code on my mind...any help ?
PHP is definitely the way to get this done. I've used the CodeIgniter php framework in a lot of my projects. It's very easy to set up and use, but feel freed to shop around to find what's best for you. I'll try not to be too CodeIgniter specific here, but if you do go this route you can check out this video on basic database function with CodeIgniter.
Basically whatever you choose to do there are going to have few basic parts. Some config area where you type in you Database name, and username and password.
Example Database Config file:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "myusername";
$db['default']['password'] = "mypassword";
$db['default']['database'] = "mydatabse";
$db['default']['dbdriver'] = "mysql";
Now that the php knows how to talk to your database it's time to get the data and send it to be displayed.
This next part is more specific to CodeIgniter, mostly because that's what I have the most experience with, but many of the other frameworks will be something similar. The next three code snips will be represent three different files. The idea is to abstract/remove the backend database stuff from the front end content. This is referred to as Model-View-Controller(MVC)
Run your query (Model):
function getData()
{
$query = $this->db->get('myTable');
return $query->result();
}
Set that data and send it to your view(Contorller):
function addReceipt()
{
$data = array();
if($query = $this->my_model->getData())
{
$data['content'] = $query;
}
$this->load->view('my_view', $data);
}
Lastly display your data by looping through records and using php echo(View):
<ul class="content">
<?php if(isset($content)) : foreach($content as $row) : ?>
<li class="<?php echo $row->liclass; ?>">
<p id="<?php echo $row->ID; ?>"><?php echo $row->paragraph1; ?></p>
<div class="<?php echo $row->divclass; ?>">
<p><?php echo $row->paragraph2; ?></p>
</div>
</li>
<?php endforeach; ?>
</ul>
This would be interesting if you showed your php code here:
but this is what you should do
<?php
mysql_connect('hostname','username','password');
mysql_select_db('dbname');
$sql = "select *from tablename";
$run = mysql_query($sql);
echo "<table>";
echo "<tr><th>NAME</th><th>SURNAME</th><th>GENDER</th><th>BIRTHDAY</th></tr>";
$i = 1;
while($row = mysql_fetch_array($run)){
if($i%2 == 0) $bgcolor = 'lightblue';else $bgcolor = 'white';
$i++;
echo "<tr style='backgroundcolor".$bgcolor."'><td>NAME</td><td>".$row['SURNAME']."</td><td>".$row['GENDER']."</td><td>".$row['BIRTHDAY']."</td></tr>";
}
echo "</table>";
?>

Categories