Welcome Guest, Not a member yet? Register   Sign In
do I really need to make an array to get result from db?
#1

[eluser]jtan[/eluser]
this works

$query=$this->db->get('product');
$products=array();
foreach($query->result() as $row)
{
$products[]=array(
'id'=>$row->id,
'product'=>$row->product
);

}
return $products;

but this doesn't work which I patterned after the sample on Codeigniter user guide:

$query=$this->db->get('product');
return $query->result():

Does anyone know why it won't load?
#2

[eluser]mddd[/eluser]
I think it does load, but the difference is that you get a list of objects in stead of a list of arrays.
So if you wrote in your view foreach ($products as $product) { echo $product['id']; } to show results from your first example,
you should use foreach ($products as $product) { echo $product->id; } to show the results from your second example.
Or you could use $query->result_array(); which also gives you a list of arrays (the same as your first example).
#3

[eluser]Twisted1919[/eluser]
Working with objects is a bit faster than working with arrays, and i believe is a more closer approach to OOP .
#4

[eluser]jtan[/eluser]
how do I work with objects from that result? any clues... since most samples I saw are arrays.
#5

[eluser]pickupman[/eluser]
Basically the same way, but instead of a array key being enclosed in brackets in single quotes, you would use ->key
Code:
//Array
$product['id'];
//Object
$product->id;
#6

[eluser]Prophet[/eluser]
Code:
function getProducts()
{
    $query = $this->db->get('product');
    return $query->result();
}

$products = getProducts(); //$products now contains $query->result();

//In the same way that you used foreach ($query->result() as $row)...
foreach ($products as $product)
{
    echo "{$product->id} - {$product->name} - {$product->price}";
}

At the end of the day, if you're more comfortable using arrays than objects... Use arrays Smile




Theme © iAndrew 2016 - Forum software by © MyBB