0

I have an id array in my controller that has checkbox input in a form in views. $toppings = $this->input->get('topping');

Array
(
  [0] => 1
  [1] => 3
  [2] => 4
)

I'm trying to get the information relevant to each id in the array from the database.

    $toppings = $this->input->get('topping');
    foreach ($toppings as $topping ) {
        $id = $topping;
        $toppinglist = $this->toppingmodel->find_topping($id);
        echo'<pre>'; print_r($toppinglist); die();

    }

Model Class -

function find_topping($id)
{
    $query = $this->db->get_where('Topping', array('id' => $id));
    return $query->row_array(); }

}

The output array i'm getting is only the data for the first id

Array
(
  [id] => 1
  [slug] => mushroom
  [toppingName] => Mushrooms
  [price] => 50.00
)

How can i get all the data relevant to each id in an array. (nested array) Thank you.

1
  • $this->db->where_in('Topping', $toppings); Commented Nov 3, 2020 at 5:35

2 Answers 2

1

Controller:-

$toppings = $this->input->post('topping');    //Array         
$toppinglist = $this->toppingmodel->find_topping($toppings);

model:-

function find_topping($idArr = array()){         //Array  
 $query = $this->db->where_in("Topping", $idArr)->get("tablename");
     return $query->result_array();
}

Note:- $idArr = array() means

make the function have a default value of array otherwise if something else is passed you'll get an error in your query.

Sign up to request clarification or add additional context in comments.

7 Comments

Still an error is thrown. Call to undefined method CI_DB_mysqli_driver::result_array().
ids are in comma seperated values in one column??
ids are in an array. The array structure is shown at the top of the question
now try with my updated answer & let me know what happens??.
Thank you so much. I'm getting the data array now
|
0

You need to make your SQL query with WHERE IN().

In Codeignitor you can use $this->db->where_in($tableName, $arrayOfVales). Learn more here

Code Example

function find_topping(array $ids)
{
    $query = $this->db->where_in('Topping', $ids);
    return $query->result_array(); 
}

3 Comments

How should i pass the id from the controller. I tried using db->where_in but now a type error is thrown saying Message: Argument 1 passed to toppingmodel::find_topping() must be of the type array, string given,
@Dilki Sasikala what you get in id or 'array` $toppings = $this->input->get('topping');
You need to send an array of Ids to function find_topping();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.