Welcome Guest, Not a member yet? Register   Sign In
Passing to json_encode an array of all the MySQL table rows generated by row_array()
#1

[eluser]Unknown[/eluser]
Hello guys, my first post here with the hope you can help me out for a problem I've been having.

What I need to do is to pass to json_encode an array, that is the result of the row_array() function.

In my model, in fact, i have a very simple function

Code:
public function tuttiProdotti()
{

  $q = $this->db->query('SELECT * FROM products');
    if( $q->num_rows() > 0 )
    {
   return $q->row_array();
    }
  
    return FALSE;

}

That gives to my controller an array with more than one row. In the function of my controller I have

Code:
if($item = $this->inventories_model->tuttiProdotti()) {
      
   $product_name = $item['name'];
   $product_cost = $item['cost'];
   $product_tax = $item['tax_rate'];
  
   $tax_rate = $this->inventories_model->getTaxRateByID($product_tax);
  
   $product = array('name' => $product_name, 'cost' => $product_cost, 'tax_rate' => $tax_rate);
  
    }
    
   echo json_encode($product);

As you may expect this gives to my json_encode datas for only one row (I think the last selected row?) while I want to pass it an array, made itself of ARRAYS (the $product variable).

Any help to find out how to achieve this, and how to retreive the data in a later phase, would be greatly appreciated.

I hope you can help me go out of this mess!
#2

[eluser]InsiteFX[/eluser]
Code:
$product = array();

if ($item = $this->inventories_model->tuttiProdotti())
{
    foreach ($item as $row)
    {
        $product_name = $row['name'];
        $product_cost   = $row['cost'];
        $product_tax    = $row['tax_rate'];
  
        $tax_rate = $this->inventories_model->getTaxRateByID($product_tax);
  
        //$product      = array('name' => $product_name, 'cost' => $product_cost, 'tax_rate' => $tax_rate);
        $product['name']     = $product_name;
        $product['cost']       = $product_cost;
        $product['tax_rate'] = $tax_rate;
    }
}

echo json_encode($product);

When dealing with data like that you need to use a foreach loop.
So it would be something like that. Not tested.
#3

[eluser]InsiteFX[/eluser]
You can read more about it here:

CodeIgniter User Guide - Generating Query Results
#4

[eluser]InsiteFX[/eluser]
Duplicate post please delete




Theme © iAndrew 2016 - Forum software by © MyBB