Welcome Guest, Not a member yet? Register   Sign In
Data type changes when selecting using Active Record
#1

[eluser]jppi_Stu[/eluser]
I'm trying to understand something...

I have a tinyint column in a MySQL table, I'll refer to it as "is_something" for the code shown below. I'm using Active Record in a model to select from that table:

Code:
function item_detail ($item_id)
{
$query = $this->db->get_where('items',array('item_id' => $item_id));
return ($query->result());
}

This is being called by a controller and being passed to a view:

Code:
$query = $this->Item_model->item_detail($item_id);
$data['this_item'] = $query[0];
$this->load->view('item_edit_v.php', $data);

In the view, I want to do some basic customization of what the user will see based on the is_something field. The field will either be a 0 or a 1. I want to generate some HTML if it is 0. However, despite it coming from a tinyint column, I have to compare it against a string. For example:

Code:
$some_html = ($this_item->is_something === 0) ? 'is zero' : 'is not zero';
# $some_html will be set to 'is not zero'

$other_html = ($this_item->is_something === '0') ? 'is character zero' : 'is not character zero';
# $other_html will be set to 'is character zero'

This is probably something obvious, and possibly not specific to CI, but I'm not getting it. Why does the tinyint value become a string value?
#2

[eluser]Walter Coots[/eluser]
I don't have a definite answer, but it may have to do with PHP's type juggling (manual). One solution is to cast it as an integer by typing (int) before using it. It's kind of annoying having to do it at the point of need, so maybe you could cast all values as the appropriate types in your model.

Code:
$is_something = (int) $is_something;
$some_html = ($this_item->is_something === 0) ? 'is zero' : 'is not zero';
#3

[eluser]Atharva[/eluser]
First of all, why are you returning records with result() function when you just need a single row? Try this:

Model
Code:
function item_detail ($item_id)
{
$query = $this->db->get_where('items',array('item_id' => $item_id));
return ($query->row());
}

Controller
Code:
$data['this_item'] = $this->Item_model->item_detail($item_id);
$this->load->view('item_edit_v.php', $data);

Not sure this will solve your problem but this is much better than your code.




Theme © iAndrew 2016 - Forum software by © MyBB