How to pass a variable from model to controller in codeigniter - php

How can I pass a variable from the model to the controller?
Here is my model:
public function edititem($id){
$query = $this->db->query('SELECT * FROM tblitem WHERE item_id = "$id"');
foreach ($query->result() as $row){
$name = $row->item_name;
$description = $row->item_description;
$price = $row->item_price;
}
And here is my controller
public function editItem(){
$this->load->helper('form');
$this->load->model('ItemModel');
$this->ItemModel->edititem($this->input->get('id'));
$name = $this->input->post('name');
$description = $this->input->post('description');
$price = $this->input->post('price');
$data['items'] = $this->ItemModel->itemlist();
$this->load->view('item/item_edit',$data);
}
In which when the user clicks "Edit Item", it will populate the form with the selected row.
<form action="<?php echo base_url().'item/edititem' ?> " method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="name" class="form-control" id="name" name="name" placeholder="Name" value="<?php echo set_value('name'); ?>">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="3" name="description"><?php echo set_value('description'); ?></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="price">Amount (in pesos)</label>
<div class="input-group">
<div class="input-group-addon">Php</div>
<input type="text" class="form-control" name="price" id="price" placeholder="Amount" value="<?php echo set_value('price'); ?>">
<div class="input-group-addon">.00</div>
</div>
</div>
<button type="submit" class="btn btn-primary">EDIT ITEM</button>
</form>

If it is from model to controller, You can make an array and store that 3 fields. (I assume there is only single row returned by your query since you are using id as where).
$result = array();
foreach ($query->result() as $row)
{
$result['name'] = $row->item_name;
$result['description'] = $row->item_description;
$result['price'] = $row->item_price;
}
return $result;
You can access it in the controller using:
$data['items']['name'];
$data['items']['description']
$data['items']['price']
Or in your view as
$items['name'];
$items['description'];
$items['price'];

Here your model looks like this
public function edititem($id){
$query = $this->db->query('SELECT * FROM tblitem WHERE item_id = "$id"');
if ($query->num_rows() > 0) {
$row = $query->row_array(); // row_array return single row and result_array return multiple row
return $row['dt'];
And your controller looks like this
public function editItem(){
$this->load->helper('form');
$this->load->model('ItemModel');
$item_details=$this->ItemModel->edititem($this->input->get('id'));
here you use foreach loop
foreach ($item_details as $key=>$value){
//do this in $data array
} //now you can use the specific data to your view.
$this->load->view('item/item_edit',$data);
}

Your Model:
This may useful if your want to return a specific 1 row without using result()
public function edititem($id){
$this->db->select('*');
$this->db->from('tblitem ');
$this->db->where('item_id ',$id);
return $query = $this->db->get()->custom_row_object(0, 'ItemModel');
}
Your Controller: Call the edititem($id) from ItemModel (your model)
public function editItem(){
$item_id=$this->uri->segment(3); //added this
$this->load->helper('form');
$this->load->model('ItemModel');
$item_details=$this->ItemModel->edititem($item_id); //added this
$data['item_name'] = $item_details->name;
$data['item_desc'] = $item_details->description;
$data['item_price'] = $item_details->price;
//now you can use the specific data to your view.
$this->load->view('item/item_edit',$data);
}
In your view, you can use the variable like:
$item_name;
$item_desc;
$item_price;
eg:
<input type="text" name="item_name" value="<?php echo $item_name;?>" />

Related

illegal string offset(codeigniter 3)

Hi been trying to retrieve records from my database, but I keep getting this error "Severity: Warning Message: Illegal string offset " in several fields.
controller
public function get_discount(){
if($this->session->has_userdata('logged_in')){
// redirect(base_url());
}
else{
$output = array();
$output['error']="failed";
$coupon_code=$this->input->post('coupon_code');
$product_price=$this->input->post('product_price');
$condition=array('coupon_code'=>$coupon_code,
'product_price'=>$product_price
);
$count['discount']= $this->Form_model->get_discount('coupon',$condition);
foreach($count['discount'] as $row)
{
echo json_encode($count['discount']);
if($count > 0){
$discount = $row['discount'] / 100;
$total = $discount * $product_price;
$array['discount'] = $row['discount'];
$array['product_price'] = $product_price - $total;
$output['success']="success";
echo json_encode($output);
}
}
}
}
this is my model
public function get_discount($data){
$sql = "SELECT * FROM coupon WHERE (coupon_code = ? ) AND status= 'valid' ";
$query = $this->db->query($sql, array($data['coupon_code']));
$result = $query->row() ;
if($query->num_rows()==1){
return $result;
}
}
This is my view
<form action="/get_discount" method="post">
<div class="form-group">
<h4 class="text-warning">*Optional</h4>
<label>Coupon Code</label>
<input class="form-control" name="coupon_code" type="text" id="coupon_code" />
<input type="hidden" value="<?php echo $product->product_price?>" id="price" />
<div id="result"></div>
<br style="clear:both;" />
<button class="btn btn-primary" id="activate">Activate Code</button>
</div>
</form>
<div class="form-group">
<label>Total Price</label>
<input class="form-control" type="number" value="<?php echo $product->product_price?>" id="total" readonly="readonly" lang="en-150" />
</div>
</div>
</div>
You're calling get_data() with too many arguments. It only $condition should be the only argument.
$count['discount']= $this->Form_model->get_discount($condition);
The error is because $data is the first parameter, which you're passing the string 'coupon' to in your call.

foreach php form issue, only updates last line

My page is showing 4 updatable items. But when Update is clicked it is only updating the last item.
I have 3 different files I'll post. I've been working on this for days.
I got some advice on what to do, but the foreach on the core page seems like I'm missing somethings, but I cannot figure out what.
Display Page
<div class="cccm-dashboard-content-inner">
<div class="row">
</div>
<div class="ccm-dashboard-content-full">
<div class="row" style="padding-bottom:6px">
<div class="col-sm-6">Product Name -or- (SKU)</div>
<div class="col-sm-6"><a>Pricing</a></div>
</div>
<?php if (count($products) > 0) {
foreach ($products as $product) {
$pID = $product->getID();
$price = $product->getBasePrice() ?>
<form role="form" class="form-inline" method="post">
<div class="row" style="border-top:1px solid #333;padding:12px 0">
<div class="col-sm-6">
<input type="text" id="pName<?= $pID ?>" name="pName[]" value="<?= $product->getName() ?>" required="required" class="form-control ccm-input-text" style="width:100%;margin:1px"/>
<input type="text" id="pSKU<?= $pID ?>" name="pSKU[]" value="<?= $product->getSKU() ?>" placeholder="No SKU Set" maxlength="100" class="form-control ccm-input-text" style="width:100%;margin:1px"/>
<strong><?= t('Edit Page Directly') ?></strong>
</div>
<div class="col-sm-6">
<div class="input-group">
<input type="number" id="changeValue<?= $pID ?>" name="pPrice[]" value="<?= $price ?>" step="0.01" class="form-control ccm-input-number" style="width:100%;margin:1px"/>
</div>
</div>
<?= $token->output('community_store') ?>
<input type="hidden" name="pID[]" value="<?= $pID ?>"/>
</div>
<div class="ccm-dashboard-form-actions-wrapper">
<div class="ccm-dashboard-form-actions">
<button class="float-end pull-right btn btn-primary" type="submit[]"><?= t('Update All Products') ?></button>
</div>
</div>
</form>
<?php }
} ?>
</div>
</div>
This is my controller page:
class Pricing extends DashboardSitePageController {
public function view() {
if ($this->request->getMethod() == 'POST') {
$return = $this->save();
if ($return) {
return $return;
}
}
$this->loadFormAssets();
$this->set('product', $product);
$this->set('page', $page);
$productsList = new ProductList();
$ListItemsPerPage = 3;
$productsList->setItemsPerPage($ListItemsPerPage);
$productsList->setGroupMatchAny(true);
$this->set('productList', $productsList);
$factory = new PaginationFactory($this->app->make(Request::class));
$paginator = $factory->createPaginationObject($productsList);
$pagination = $paginator->renderDefaultView();
$this->set('products', $paginator->getCurrentPageResults());
$this->set('pagination', $pagination);
$this->set('paginator', $paginator);
$site = $this->getSite();
}
public function save() {
$data = $this->request->request->all();
if ($this->request->request->all() && $this->token->validate('community_store')) {
$product = ProductPricing::savePricing($data);
$event = new ProductEvent($originalProduct, $product);
Events::dispatch(ProductEvent::PRODUCT_UPDATE, $event);
if ($data['pID']) {
$this->flash('success', t('All Listed Products Updated'));
}
}
}
public function loadFormAssets() {
$this->requireAsset('css', 'select2');
$this->requireAsset('javascript', 'select2');
$this->set('al', $this->app->make('helper/concrete/asset_library'));
$this->requireAsset('css', 'communityStoreDashboard');
$this->requireAsset('javascript', 'communityStoreFunctions');
$pageType = PageType::getByHandle('store_product');
}
protected function getHeaderSearch($groupList, $gID) {
if (!isset($this->headerSearch)) {
$this->headerSearch = $this->app->make(ElementManager::class)->get('products/search', 'community_store', ['groupList'=>$groupList, 'gID'=>$gID]);
}
return $this->headerSearch;
}
}
This is the core page:
class ProductPricing extends Product {
/**
* #return \Concrete\Package\CommunityStorePricing\Src\CommunityStore\Product\ProductPricing
*/
public static function savePricing($data) {
$counter = 0;
foreach($data['pID'] as $aProductID) {
echo $data['pPrice'][$counter];
$product = self::getByID($data['pID'][$counter]);
$product->setName($data['pName'][$counter]);
$product->setSKU($data['pSKU'][$counter]);
$product->setPrice($data['pPrice'][$counter]);
$product->save($counter);
return $product;
$counter++;
}
}
}
return __NAMESPACE__;
Thank you Barman, this worked perfectly.
You're creating a separate form for each item. If you want to update all items at once, put the outside the foreach loop.
Take return $product out of the foreach loop. It's exiting the function after updating the first item.

Codeigniter has a error with foreach loop

my problem is that, when i try to get a product detail from the table, i click on the product's name and it will lead me to product_detail, but when i run i show the problem is:
Invalid argument supplied for foreach()
Can you have a look and tell me what can i do to solve this problem?
this is my view:
<?php foreach ($prod_detail as $ud) { }?>
<form method="POST" name="fr_update">
<input type="hidden" name="id_sp" value="<?php echo $ud->id_sp; ?>">
<div class="row" style="margin-bottom: 10px">
<div class="col-md-2">
<p>Tên sản phẩm</p>
</div>
<div class="col-md-4">
<input type="text" class="form-control" style="max-width: 365px;" name="ten_sp" readonly value="<?php echo $ud->ten_sp;?>">
</div>
<div class="col-md-2">
<p>Ngày sản xuất:</p>
</div>
<div class="col-md-4" style="padding-left: 0px">
<input align="left" type="date" class="form-control" style="max-width: 365px;" name="ngay_sx" readonly value="<?php echo $ud->ngay_sx;?>"/>
</div>
And this is my controller
function prod_detail($id_sp){
$data['main_content'] = 'backend/home/manproduct/prod_detail_view';
$this->load->model('product_model');
$data['prod_detail'] = $this->product_model->getProdDetailByProdId($id_sp);
$data['rows']= $this->membership_model->getUserData();
$data['row']= $this->product_model->getProdData();
$this->load->view('includes/admin/template', $data);
}
And this is my product_model
function getProdDetailByProdId($ten_sp){
$this->db->where('ten_sp', $ten_sp);
$query = $this->db->get('products');
if ($query->num_rows() == 1) {
$data = $query->row();
return $data->$id_sp;
}
}
function getProdData(){
$this->db->where('ten_sp', $ten_sp);
$query = $this->db->get('products');
if($query->num_rows()>0){
foreach ($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
You Are fetching only one row not an array..
function getProdDetailByProdId($ten_sp){
$this->db->where('ten_sp', $ten_sp);
$query = $this->db->get('products');
if ($query->num_rows() == 1) {
$data = $query->row(); //here
return $data->$id_sp;
}
}
$data['prod_detail'] = $this->product_model->getProdDetailByProdId($id_sp);
This Wont Give You an array Its only gives You row..
$query->row();
This method returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an object.
So no need to use foreach if you still want to use foreach then use $query->result() instead of $query->row()

passing to model through controller in codeigniter?

I want to select an option of product categories from dropdown menu and show products that have that specific category.
Here is the form part from my view:
<?php $attributes = array('method'=>"POST", "class" => "myc", "id" => "myc", "name" => "dropdwn");
echo form_open_multipart('frontend/home/display', $attributes); ?>
<div class="form-group">
<div class="col-sm-9">
<select class="form-control" name="category" onchange="this.form.submit();" />
<option value="" <?php echo set_select('category', 'zero', TRUE); ?>>Categories...</option>
<option value="phone" >Phones</option>
<option value="laptops">Laptops</option>
<option value="accessories" >Accessories</option>
</select>
</div>
</div>
<?php echo form_close(); ?>
As you can see I get the option from dropdown through onchange="this.form.submit();
(if it's not a good idea please suggest other way to do, I just didn't want to use ajax, as I'm not so good at it yet, anyhow suggest what seems better).
Then in my controller I get the option and convert it to array, to use it in my model.
controller part:
public function display($sort_by='product_id', $sort_order='asc', $offset = 0)
{
$this->load->model('model_product');
$selected = implode(" ", $this->input->post());
//var_dump($selected);
$results = $this->model_product->fetch($selected, $limit, $offset, $sort_by, $sort_order);
$data['products'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
//and then goes pagination part, I guess no meaning posting it, as it works fine.
}
My model:
function fetch($selected, $limit, $offset, $sort_by, $sort_order)
{
$sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
$sort_columns = array('product_id', 'name', 'description', 'category', 'country', 'price');
$sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'product_id';
//actual results query
$q = $this->db->select('product_id, name, description, category, country, price, img_name, thumb_name')
->from('products')
->where('category', $selected)
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
$ret['rows'] = $q->get()->result();
var_dump($ret['rows']);
die;
//count query
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('products');
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
Here I get no results, probobly because where clause returns no result.
However if I change the where clause such as ->where('category', 'phones') it shows only phones. So how can I pass selected value to the query correctly?
i wil help you.
View file
<div class="box-header">
<h3 class="box-title">Enter Category Details</h3>
</div>
<?php
echo validation_errors(); $attributes = array('id' => 'formCategory','name'=>'formCategory');
?>
<?php echo form_open_multipart(base_url().'moderator/B2BCategory/addcategory'); ?>
<div class="box-body">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="txtcatname">Title of Category :</label>
<input type="text" name="txtcatname" class="form-control" id="txtcatname" placeholder="Category Name " required="required">
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="categorysection">Section of the Category :</label>
<select class="form-control" name="categorysection" required>
<option value="" >----Select------</option>
<option value="1">Laptop</option>
<option value="2">Phone</option>
<option value="3">Accessories</option>
</select>
<input type="submit" name="selsub" class="btn btn-primary">
</div>
</div>
</div>
Controller
public function addcategory() {
$this->load->helper(array('form', 'url'));
$this->load->view('moderator/templates/header');
$this->load->view('moderator/templates/sidebar');
if ($this->input->post('selsub')) {
$data = array('ctg_name' => $this->input->post('categorysection'));
$this->b2bcategory_model->form_insert($data);
}
In Model
public function form_insert($data){
$this->db->insert('jil_category', $data);
}
To display output from table,just use
public function viewall()
{
$this->db -> select('*');
$this -> db -> from('jil_category');
$query = $this -> db -> get();
return $query->result();
}
From
$selected = implode(" ", $this->input->post());
To
$selected = $this->input->post('category');
By the way, echo & var_dump() would be very useful in debugging your controller and/or model.

Cannot update product table getting You must use the "set" method to update an entry

im still learning codeigniter and have come up with a problem. That is
You must use the "set" method to update an entry.
I am trying to update a table : product which contains product_name, product_desc etc columns below are my controller ,view and model .. i cannot figure out what am i doing wrong .. I always checked out print_r($array); it gives me an empty array ... although i do get product details displayed in the input fields on the link : ci/index.php/admin/product/1 ..
posting half code for view as the view code is long ..
Controller :
//**** For editing product ****//
public function edit_products(){
$data = array ('product_name'=>$this->input->post('product_name'),
'product_desc'=>$this->input->post('product_desc'),
'product_stock'=>$this->input->post('product_stock'),
'product_sku'=>$this->input->post('product_sku'),
'inventory_date'=>$this->input->post('inventory_date'),
'product_price'=>$this->input->post('product_price'),
'featured_product'=>$this->input->post('featured_product'),
'best_seller'=>$this->input->post('best_seller'),
'brand_id'=>$this->input->post('brand_id'),
);
$upd_pr = $this->mainmodel->update_product($_POST);
if($upd_pr){
$this->session->set_flashdata('messages', 'Updated Sucessfully');
redirect('admin/editing_products');
}else{
$this->session->set_flashdata('error', 'Updation Failed');
redirect('admin/editing_products');
}
}
public function editing_products(){
$data['product']=$this->mainmodel->set_pro2();
//$data['images'] = $this->products->images($id);
$data['content']='admin/edit_products';
$this->load->view('admin/main',$data);
}
Model :
/*for update Product*/
public function update_product($array){
extract($array);
//print_r($array);
//die;
$this->db->update('product',array('product_name'=>$product_name,'product_desc'=>$product_desc,'inventory_date'=>$inventory_date,'product_price'=>$product_price,'featured_product'=>$featured_product,'best_seller'=>$best_seller,'brand_id'=>$brand_id));
$this->db->update('product');
return ;
}
function set_pro2(){
$q = $this->db->query('SELECT * FROM product,product_image,category_product WHERE product.product_id = category_product.product_id AND product.product_id = 1 LIMIT 1');
if($q->num_rows() > 0){
foreach($q->result() as $row){
$data[] = $row;
}
return $data;
}
}
View :
<form class="form-horizontal form-row-seperated" enctype="multipart/form-data" action="<?php echo site_url('admin/edit_products') ?>" method="post">
<div class="form-group">
<?php foreach($product as $pro){ ?>
<label class="col-md-2 control-label">Name:<span class="required">
* </span>
</label>
<div class="col-md-10">
<input type="text" class="form-control" name="product_name" placeholder="" value="<?php echo $pro->product_name; ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Description: <span class="required">
* </span>
</label>
<div class="col-md-10">
<input type="text" class="form-control" name="product_desc" value="<?php echo $pro->product_desc; ?>">
</div>
</div>
In some cases codeigniter updates / inserts require this->db->set if in array. I also would not recommend placing two db->update to the same table as you have added on model.
Active record guide http://www.codeigniter.com/user_guide/database/active_record.html
Update
// $brand_id = 0, $data are from the edit function on controller
public function name($brand_id = 0, $data) {
$product_name = $this-input->post('product_name');
$product_desc = $this-input->post('product_desc');
$inventory_date = $this-input->post('inventory_date');
$product_price = $this-input->post('product_price');
$featured_product = $this-input->post('featured_product');
$best_seller = $this-input->post('best_seller');
$data = array(
'product_name'=> $product_name,
'product_desc'=> $product_desc,
'inventory_date'=>$inventory_date,
'product_price'=>$product_price,
'featured_product'=> $featured_product,
'best_seller'=> $best_seller,
'brand_id'=> $this->uri->segment(what_ever)
);
$this->db->set($data);
$this->db->update('product');
}
Or insert
$data = array(
'product_name'=> $product_name,
'product_desc'=> $product_desc,
'inventory_date'=>$inventory_date,
'product_price'=>$product_price,
'featured_product'=> $featured_product,
'best_seller'=> $best_seller,
'brand_id'=>$brand_id
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert('product');
Post Update
Set routes $route['function/edit/(:any)'] = 'folder/products_list/edit/$1';
If need to update a product you need to set a function called edit on the
Model Get
public function model_get_products() {
return $this->db->get($this->db->dbprefix . 'products')->result_array();
}
Controller for uri segment help http://www.codeigniter.com/user_guide/libraries/uri.html
public function edit() {
Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('what ever');
if ($this->form->validation->run() == TRUE) {
$this->load->model('folder/model_update_product');
//Example uri segment admin/product_list/edit/id_number $this->uri->segment('4')
$this->model_update_product->name($this->uri->segment('what_ever_is'), $this->input->post())
redirect('function/product_list');
} else {
// Load Your Form View i.e. $this->get_form();
}
}
public function index() {
$this->load->model('folder/model_get_products');
$results = $this->model_get_products->get();
$data['products'] = array();
//Example uri segment admin/product_list/edit/id_number $this->uri->segment('4')
// Add What Else You Need to here and then you can add it to view
foreach($results as $result) {
$data['products'][] = array(
'brand_id' => $result[brand_id],
'edit' => site_url('controller_name/edit'). '/' .$result[brand_id] // site_url must match what you set in routes for edit.
);
}
return $this->load->view('folder/products_list', $data);
}
public function get_form() {
//Example uri segment admin/product_list/edit/id_number $this->uri->segment('4')
// Make sure you set another model function in your get model where can get by id.
$product_info = $this->get_products_by_id->get($this->uri->segment('4'));
$product_name = $this->input->post('product_name');
if (isset($product_name)) {
$data['product_name'] = $product_name; // for name="" in input
} elseif (!empty($product_info)) {
$data['product_name'] = $product_info['product_name']; // for value="" in input
} else {
$data['product_name'] = '';
}
$this->load->view('folder/product_form', $data);
product form contents
}
view product list
<form>
<table>
<thead>
</thead>
<tbody>
<?php if ($products) { ?>
<?php foreach ($products as $product) { ?>
<tr>
<td><?php echo $product['brand_id'];?></td>
<td> Edit Product</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</form>

Categories