Reputation: 5367
So I have this code block in my controller (I know, db stuff should be in model..I'll transfer it over there once working). Searches the database for a "subscription" and echos in the view. That works. However, in my view, I want to add an IF statement like the second block of code below - but it's not working. Suggestions? In other words, how would you write the IF statement in the view? Pretty sure the query
portion is incorrect...
// displays current subscription in view
$userid = $this -> session -> userdata('user_id');
$this -> db -> select('subscription');
$this -> db -> where ('id', $userid);
$query = $this -> db -> get('subscriptions');
if($query -> result() == TRUE) // if subscription exists for user, display:
{
foreach ($query->result() as $row)
{
$data['packagename'] = $row->subscription;
}
}
In view:
<?php if($query -> result() == TRUE) : ?>
<? echo $packagename; ?>
<?php endif ?>
Upvotes: 0
Views: 73
Reputation: 6078
Basing on what I see from your code, I am getting the feeling that you think whatever variables you use in your controller are automatically available within your view. This is not the case. You should be setting your variables and performing your logic in the controller and passing what you want displayed to your view.
This is what your controller should look like:
// displays current subscription in view
$userid = $this -> session -> userdata('user_id');
$this -> db -> select('subscription');
$this -> db -> where ('id', $userid);
$query = $this -> db -> get('subscriptions');
if($row = $query -> result()) // if subscription exists for user, display:
{
$data['packagename'] = $row->subscription;
}
$this->load->view("yourview", $data);
You do not need a foreach
as you are pulling by ID - you only want one record.
Then, in your view, just display it like this:
<?php if (!empty($packagename)) echo $packagename;?>
Upvotes: 1
Reputation: 599
Keep your DB logic out of your views, that is what models are for. If you're already passing $packagename into your view, why not simply test for it?
<?php if ( isset($packagename) ) : ?>
<? echo $packagename; ?>
<?php endif; ?>
Or, if you can use short_open_tags:
<? if ( isset($packagename) ) : ?>
<?= $packagename ?>
<? endif; ?>
Upvotes: 5
Reputation: 227280
$query->result()
does not return a boolean, it returns an array ob objects.
To check if the query returned a result, use num_rows()
.
if($query->num_rows() > 0){
foreach ($query->result() as $row){
}
}
Also, you shouldn't pass your $query
object to the view, instead use isset
to see if the variable is there:
<?php if(isset($packagename)): ?>
<?php echo $packagename; ?>
<?php endif ?>
Upvotes: 5