php - foreach array insert to database -
i have 3 tables. category,ingredient , category_ingredient. want id's of category , ingredient inserted category_ingredient. error this:
this code:
view:add_ingredients.php
<?php echo form_open('dashboard/uploadingredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?> <div class="form-group"> <div class="col-sm-10"> <select class="form-control" name="ingredient_category"> <option selected disabled>select ingredient category</option> <option value="all">all</option> <?php foreach($this->products_model->getcategory() $row): ?> <option value="<?php echo $row->category_id ?>"><?php echo $row->name; ?></option> <?php endforeach; ?> </select> </div> </div> <div class="form-group"> <div class="col-sm-10"> <textarea class="form-control" name="ingredients" rows="5" placeholder="ingredients (ex. onion, oil, pasta)"></textarea> </div> </div> <div class='form-group'> <div class="col-sm-10"> <button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> save ingredient</button> </div> </div> <?php echo form_close(); ?>
controller: dashboard.php
public function uploadingredients() { foreach(explode(',', $this->input->post('ingredients')) $key => $value) { $savedata[] = array('ingredient_id' => null, 'name' => trim($value) ); } // var_dump($savedata); die(); $ingredient_id = $this->products_model->saveingredients($savedata); foreach (explode(',', $this->input->post('ingredient_category')) $key => $value) { $joindata[] = array( 'ingredient_id' => $ingredient_id, 'category_id' => trim($value) ); } //var_dump($joindata); die(); $this->products_model->savecategoryingredients($joindata); redirect('dashboard/add_ingredients'); }/* end of upload_file() */
model: products_model.php
public function saveingredients($data) { foreach($data $row => $value) { $this->db->insert('ingredient', $value); $insert_id[] = $this->db->insert_id(); } return $insert_id; } public function savecategoryingredients($data) { foreach($data $row => $value) { $this->db->insert('category_ingredient', $value); $insert_id[] = $this->db->insert_id(); } return $insert_id; }
you're treating $ingredient_id
string it's array. name variables type i'm expecting don't confused... example, $ingredient_id_array
.
// var_dump($savedata); die(); $ingredient_id_array = $this->products_model->saveingredients($savedata); foreach (explode(',', $this->input->post('ingredient_category')) $key => $value) { foreach ( $ingredient_id_array $key => $str ){ $joindata[] = array( 'ingredient_id' => intval( $str ), 'category_id' => intval( trim($value) ) ); } }
Comments
Post a Comment