codeigniter get array data in controller - codeigniter

I have sql query in controller, this query produces number of rows.
$q1 = $this->db->query("SELECT product_code,product_quantity FROM tbl_order_details WHERE order_id='$order_no' AND location='$location'")->row();
foreach($q1 as $v_barcode){
$result = $this->settings_model->update_cancel_stock($v_barcode->product_code,$v_barcode->product_quantity);
}
then i pass this data to my model,
public function update_cancel_stock($code,$qty)
{
$this->db->set('product_quantity', $qty , FALSE);
$this->db->where('product_id', $order );
$this->db->update("tbl_inventory6");
}
but no any update. please check above code. thanx

Try this
$cond = array("order_id" => $order_no, "location" => $location);
$q1 = $this->db->select("product_code,product_quantity")->from("tbl_order_details")->where($cond)->row();
$result = $this->settings_model->update_cancel_stock($q1->product_code,$q1->product_quantity);
and then model ($code was not used)
public function update_cancel_stock($code,$qty){
$this->db->set('product_quantity', $qty , FALSE);
$this->db->where('product_id', $code);
$this->db->update('tbl_inventory6');
}

You are using row() function of Active Record. It already return only one row. So there is no requirement of foreach. Try this:
$q1 = $this->db->query("SELECT product_code,product_quantity FROM tbl_order_details WHERE order_id='$order_no' AND location='$location'")->row();
$result = $this->settings_model->update_cancel_stock($q1->product_code,$q1->product_quantity);
If you are getting multiple records and you are using foreach, you should use result().
$q1 = $this->db->query("SELECT product_code,product_quantity FROM tbl_order_details WHERE order_id='$order_no' AND location='$location'")->result();
foreach($q1 as $v_barcode){
$result = $this->settings_model->update_cancel_stock($v_barcode->product_code,$v_barcode->product_quantity);
}

Related

How can I paginate an array of objects in Laravel?

I'm building an application using Laravel 4.2. I have a model for units and another for users and pivot table user_units. Every user in this application can select a unit and add it to his favorite list then he can publish this unit with his information as an ad.
I want to select all units published by all users
The user_units (pivot) table has the following columns:
id
user_id
unit_id
publish
adtype
addinfo
created_at
updated_at
With relations methods on models
public function users() {
return $this->belongsToMany('User', 'user_units')
->withPivot('id','publish', 'adtype', 'addinfo');
}
public function units() {
return $this->belongsToMany('Unit', 'user_units')
->withPivot('id','publish', 'adtype', 'addinfo');
}
My query to select all published units by all users
// Get all published units by users for sale.
$users = User::all();
$publishedSaleUnits = [];
foreach($users as $user){
$userUnits = $user->units()->orderBy('adtype', 'desc')->get();
if(count($userUnits)){
foreach($userUnits as $unit){
if($unit->pivot->publish == 1 && $unit->unit_purpose_id == 1){
if( $unit->pivot->adtype ){
//push all featured ads onto the beginning of array
array_unshift($publishedSaleUnits, $unit);
}else{
//push all normal ads onto the end of array
array_push($publishedSaleUnits, $unit);
}
}
}
}
}
Now I got the result but I can't use pagination with results because it's an array of objects.
So is there any better solution to get all published units by user with pagination?
according to this article
https://www.itsolutionstuff.com/post/how-to-create-pagination-from-array-in-laravelexample.html
you can paginate your array by creating a custom method and using LengthAwarePaginator
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class PaginationController extends Controller
{
public function index()
{
$myArray = [
['id'=>1, 'title'=>'Laravel CRUD'],
['id'=>2, 'title'=>'Laravel Ajax CRUD'],
['id'=>3, 'title'=>'Laravel CORS Middleware'],
];
$data = $this->paginate($myArray);
return view('paginate', compact('data'));
}
public function paginate($items, $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
}
Your approach to query the data is extremely inefficient. Fetch your data in one query. Nested traversing is not only hard to read but also a performance killer.
To the pagination problem:
Laravel provides a Pagignator Factory. With it you will be able to build your own Paginator with your own data.
It's as easy as
$units = Paginator::make($unit, count($unit), 10);
if you're using the Facade. Otherwise Illuminate\Pagination\Factory is the class you are looking for.
You can try my code with your own array,
$page = isset($request->page) ? $request->page : 1; // Get the page=1 from the url
$perPage = $pagination_num; // Number of items per page
$offset = ($page * $perPage) - $perPage;
$entries = new LengthAwarePaginator(
array_slice($contact_list, $offset, $perPage, true),
count($contact_list), // Total items
$perPage, // Items per page
$page, // Current page
['path' => $request->url(), 'query' => $request->query()] // We
need this so we can keep all old query parameters from the url
);
I got a better solution to paginate array result and I found the answer here
Paginator::make function we need to pass only the required values instead of all values. Because paginator::make function simply displays the data send to it. To send the correct offset paginated data to the paginator::make, the following method should be followed
$perPage = 5;
$page = Input::get('page', 1);
if ($page > count($publishedSaleUnits) or $page < 1) { $page = 1; }
$offset = ($page * $perPage) - $perPage;
$perPageUnits = array_slice($publishedSaleUnits,$offset,$perPage);
$pagination = Paginator::make($perPageUnits, count($publishedSaleUnits), $perPage);
this code work for me on laravel 8
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
public function paginate($items, $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
according to this refrence https://www.itsolutionstuff.com/post/how-to-create-pagination-from-array-in-laravelexample.html

CodeIgniter pass variables form controller to model

Ok I want to pass two variables from a controller to a model but I get some kind of error. Am I passing variables on right way? My syntax is:
Controller:
public function add_tag(){
if(isset($_POST['id_slike']) && isset($_POST['id_taga'])){
$slika = $_POST['id_slike'];
$tag = $_POST['id_taga'];
$this->load->model("Member_model");
$res = $this->Member_model->add_tags($slike, $tag);
foreach ($res->result() as $r){
echo $r->name;
}
}
else{
echo "";
}
}
Model:
public function add_tags(){
$data = array(
'tags_id' => $tag ,
'photos_id' => $slika
);
$check = $this->db->query("SELECT tags_id,photos_id FROM bridge WHERE bridge.tags_id='{$tag}' AND bridge.photos_id={$slika} ");
if($check->num_rows()==0){
$this->db->insert('bridge',$data);
$res = $this->db->query("SELECT name FROM tags where `tags`.`id`='{$tag}' ");
return $res;
}
}
you are passing variables correctly, but do not get them correctly in the model, which should look like this:
public function add_tags($slike, $tag){
//your other code
}
The following code write on the controller file:-
$data = array();
$this->load->model('dbmodel');
$data['item'] = $this->dbmodel->getData('*','catagory',array('cat_id'=>21));
$this->load->view('listing_view', $data);
The following code write on the dbmodel file:-
public function getData($cols, $table, $where=array()){
$this->db->select($cols);
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
$result = $query->result();
return $result;}

How can I use CodeIgniter form dropdown function?

codeIgniter form_dropdown() function can receive only associative array but I have multi dimension array by using result_array() function. How can I fetch my data on form_dropdown() function?
Let's say you want a dropdown of items, using result_array():
$query = $this->db->query("SELECT id, item_name FROM items");
$options = array();
foreach ($query->result_array() as $row){
$options[$row['id']] = $row['item_name'];
}
echo form_dropdown('my_items_dropdown', $options, '1');
I have extended the class DB_result.php in system/database with this new function
public function dropdown_array($id_field = FALSE, $list_field = FALSE)
{
$result = array();
if ($id_field === FALSE || $list_field === FALSE) return $result;
$array = $this->result_array();
foreach ($array as $value) {
$result[$value[$id_field]] = $value[$list_field];
}
return $result;
}
Now you can simply call from every Model class your new function to generate a dropdown-compliant array like this:
$customers = $this->db->get('customers');
$result = $customers->dropdown_array('id', 'name');
return $result;

How to get a value from the last inserted row using Codeigniter

Is there any codeigniter function to do this?
try this code:
$this->db->insert_id();
Refer:
https://www.codeigniter.com/user_guide/database/helpers.html
There is no special function for that. But you can get the id of row that you've just inserted and then get it's data:
$this->db->insert('table_name', $data);
$id = $this->db->insert_id();
$q = $this->db->get_where('table_name', array('id' => $id));
return $q->row();
I have tips for you. When you want to insert data, please return your data array and you can edit it.
public function set_alb_photos() {
$data = array(
'alp_title' => $this->input->post('alp_title'),
'alp_file_location' => $this->input->post('alp_file_location'),
'alp_album_id' => $this->input->get('alb_id'),
'alp_created_at' => date("Y-m-d H:i:s"),
'alp_updated_at' => date("Y-m-d H:i:s")
);
$this->db->insert('alb_photos', $data);
return $data;
}
I hope this help.
Use Active Record method after insertion. return last inserted id
function insert($data)
{
$this->db->insert('tablename', $data);
return $this->db->insert_id();
}
Here is reference
This will help you to get last inserted row from the table.
$last = $this->db->order_by('id',"desc")->limit(1)->get('tablename')->row();
print_r($last);
You can get inserted data by below code,
$query = $this->db->get_where('table1', array('id' => $id)); //get inserted data
return $query->result_array();
Refer:https://www.codeigniter.com/user_guide/database/query_builder.html
What about :
$this->db->get('mytable', 1,0)
Try this only with active record of codeigniter. This code gives you the last row of your table.
$this->db->limit(1);
$this->db->order_by('id','desc');
$query = $this->db->get('tablename');
return $query->result_array();
Try this depending on the options and return :
$data = {} //your array;
// now if your $data array contained all the values of the new row just do this
function yourFunction(){
// insert into array into db
$this->db->insert('table_name', $data);
// get created rows id
$id = $this->db->insert_id();
// update your $data array with the new generated id and return it
$data['id'] = $id;
return $data;
}
// Option 2: if row has fields that auto populates (example current timestamp)
function yourFunctionAlt(){
// insert into array into db
$this->db->insert('table_name', $data);
// get created rows id
$id = $this->db->insert_id();
// get row as a array
$_rowArray = $this-db->get_where('table_name',array('id'=>$id)->row_array();
return $_rowArray;
// or get as a object
$_Object = $this->db->get_where('table_name',array('id'=>$id);
return $_Object;
}

Codeigniter: Can I return multiple values from the same function?

I would like to return the query results along w/ the row count without having to run multiple queries. Is this possible in Codeigniter? The following works for returning the query results, but is it possible to also count the number of entries found?
Controller:
$data['records'] = $this->item_model->searchItem($item_name);
Model:
$query = $this->db->query($sql, array($this->user_id, '%'.$item_name.'%'));
return $query->result();
$bindings = array($this->user_id, '%'.$item_name.'%');
$records = $this->db->query($sql, $bindings)->result();
return array(
'records' => $records,
'count' => count($records),
);
Then, in your controller:
$query = $this->item_model->searchItem($item_name);
$data['records'] = $query['records'];
$data['count'] = $query['count'];
Option one
$query = $this->db->query($sql, array($this->user_id, '%'.$item_name.'%'));
$data['result'] = $query->result();
$data['rows'] = $query->num_rows();
return $data;
Option two
// model
$query = $this->db->query($sql, array($this->user_id, '%'.$item_name.'%'));
return $query;
// controller
$data['query'] = $this->item_model->searchItem($item_name);
// then you have $data['query']->result();
// and $data['query']->num_rows();
You can send as many variables from a function as you want ..However plz remember that a function is supposed to do one UNIT of work . thus this rule must not be violated.
we can used contrel structure
if this {return A;} elseif () {return B;} else {return C;}
ALso we can send (bundle) variables in an array and send

Resources