Codeigniter:How to get the last inserted id? - mysql

Hi I am using codeigniter.I need to get the last inserted id and increment it and use it in my view page,
My controller code:
public function add_tickets()
{
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
$insert_id = $this->billing_model->store_bill($data_to_store);
/*Here I am tring to get the last inserted id*/
for ($i = 0; $i < count($pid_array); $i++) {
if(isset($pid_array[$i])&& $pid_array[$i]!=""){
$data_to_store = array(
'id' => $insert_id +1,
'employee' => $emp_array[$i],
'start_time' => $start_array[$i],
'pid' => $pid_array[$i],
'total' => $total_array[$i],
'status' => $button_status,
);
$this->billing_model->store_bill($data_to_store);
}
}
$data['ticket_new_id'] = $data_to_store['id'];
$data['bill']=$this->billing_model->get_bill();
$data['main_content'] = 'admin/billing/list';
$this->load->view('includes/template', $data);
}
This is my controller function where I insert my bill.
Here is my model function,
function store_bill($data)
{
$insert = $this->db->insert('bill', $data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Here I am using $this->db->insert_id() to get the last inserted id.
I am getting a error like this,
You must use the "set" method to update an entry.
Filename: C:\xampp\htdocs\elfanto\elfanto_billing\system\database\DB_active_rec.php
Line Number: 1174
Can someone help me? Thanks in advance

I think this is your solution:
<?php
public function add_tickets()
{
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
/*beore inserting first get the last ID of the table*/
$this->db->select('*');
$this->db->from('bill');
$this->db->order_by('id','desc');
$result = $this->db->get()->result();
$last_id = $result[0]->id;//This is the last ID of the table
/*now insert the data with incremented ID and send it to your view */
$data_to_store = array(
'id' => $insert_id +1,
'employee' => $emp_array,
'start_time' => $start_array,
'pid' => $pid_array,
'total' => $total_array,
'status' => $button_status,
);
$this->billing_model->store_bill($data_to_store);
$insert_id = $last_id + 1;//this will be your last inserted ID
$data['ticket_new_id'] = $insert_id ;
$data['bill']=$this->billing_model->get_bill();
$data['main_content'] = 'admin/billing/list';
$this->load->view('includes/template', $data);
}
For more reference how to get last ID using codeigniter check this

I have check your code not initialize the variable
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
// $data_to_store is not initialized and you are trying to store the value that's why it give you error
$insert_id = $this->billing_model->store_bill($data_to_store);

Related

SQLSTATE[42S22]: Unknown Column in 'where clause'

Error Image
Working on a Multi vendor website . Suddenly got this error when shop/vendor user want to login no problem normal user Here two type user one is vendor or ShopOwner/ another one normal Customer when vendor want to logging got this error. But normal user no Problem facing for login. Added new column but problem is continue SQL integrity Error.
Query: (SQL: select * from `shops` where `user_shops` = 233 limit 1)
Here is Login Controller.
Details for Login Controller
public function userlogin(Request $request){
$data = Cart::getContent();
$this->validate($request, [
'email' => 'required',
'password' => 'required',
],[
'email.required' => 'Email not matched with Database!',
'password.required' => 'Password not matched with Database!',
]);
$checkUserInput = filter_var($request->input('email'), FILTER_VALIDATE_EMAIL)?'email': 'username';
$user = Auth::guard('web')->attempt([$checkUserInput => $request->email,'password'=>$request->password]);
if($user == 'true'){
if(Auth::user()->is_activated == 1){
if(count($data)>0){
if(count(Cart::session(Auth::user()->id)->getContent())>0){
foreach ($data as $key => $value) {
if(!Cart::session(Auth::user()->id)->get($value->id) ){
Cart::session(Auth::user()->id)->add($value->id, $value->name,$value->price,$value->quantity, $value->image,array('color' => $value->attributes->color));
}else{
Cart::session(Auth::user()->id)->update($value->id, array(
'quantity' => array(
'relative' => false,
'value' => $request->quantity
),
'attributes' => array(
'color' => $value->attributes->color
),
));
}
}
}else{
foreach ($data as $key => $value) {
Cart::session(Auth::user()->id)->add($value->id, $value->name,$value->price,$value->quantity, $value->image,array('color' => $value->attributes->color));
}
}
}
if(Auth::user()->user_type == 2){
$model = Shop::where('user_id',Auth::user()->$user_id)->first();
if($model){
if($request->previous){
return redirect()->route('neneMart.dashboard');
}else{
return Redirect::to($request->previous);
}
}else{
if(empty($request->previous)){
return redirect()->route('create-shop');
}else{
return Redirect::to($request->previous);
}
}
}else{
if(empty($request->previous)){
return redirect()->route('home');
}else{
return Redirect::to($request->previous);
}
}
}
else{
return redirect()->route('user-login')->with(Auth::logout())->with('error', 'User email has not been activated yet!');
}
}else{
return redirect()->route('user-login')->with('error', 'Whoops! Wrong Email or Username or Password !');
}
}`
ROUTE
Route:: get('user-login', 'Auth\LoginController#usershowLoginForm')->name('user-login');
Route:: post('userLogin', 'Auth\LoginController#userlogin')->name('userLogin');
Shop Management Controller
public function index()
{
$shop = Shop::where('user_id',Auth::user()->id)->first();
$model = ShopManagement::where('shop_id','Nenemart-'.$shop->id)->first();
$shopid = 'Nenemart-'.$shop->id;
$agent = new Agent();
if($agent->isMobile() || $agent->isTablet()){
return view('mobile.mart.shopmanagemnt',compact('model','shopid'));
}else{
return view('frontend.mart.shopmanagemnt',compact('model','shopid'));
}
}
public function vendorShop(){
$shop = Shop::where('user_id',Auth::user()->id)->first();
$model = ShopManagement::where('shop_id','Nenemart-'.$shop->id)->first();
$vendorProducts = Product::orderBy('id', 'dese')->where('created_by', $shop->id)->where('type', 1)->get();
$agent = new Agent();
if($agent->isMobile() || $agent->isTablet()){
return view('mobile.mart.vendorShop',compact('model', 'vendorProducts'));
}else{
return view('frontend.mart.vendorShop',compact('model', 'vendorProducts'));
}
}
ShopManagement Model
protected $table = 'shop_management';
protected $primaryKey = 'id';
public static function getImage($shop_id){
$model = Self::where('shop_id','Nenemart-'.$shop_id)->first();
if($model){
return $model->shop_logo;
}else{
return '';
}
}
}
**Shop Model **
<?php
namespace App\Model\Frontend;
use Illuminate\Database\Eloquent\Model;
use Session;
use App\Model\Product;
use App\Model\MobileColor;
use App\Http\Controllers\HomeController;
use Auth;
use DB;
class Shop extends Model
{
protected $fillable = [
'user_id', 'shop_name', 'complex_name', 'brand_category_id', 'shop_mobile', 'shop_phone', 'trade_license', 'address', 'city', 'zipcode', 'opening_day', 'opening_time', 'closing_time'
];
public static function checkShopIsVerified($user_id){
$model = Self::where('user_id',$user_id)->where('status',1)->first();
if($model){
return true;
}else{
return false;
}
}
public static function getTodayOrder(){
$shop = Shop::where('user_id',Auth::user()->id)->first();
if($shop){
$data = DB::select("SELECT po.*, pod.id as pod_id,pod.product_id,pod.color_id,pod.quantity,pod.price,pod.status as p_status,p.product_code,p.model,p.type FROM product_order as po RIGHT JOIN product_order_details as pod ON po.id = pod.order_id JOIN products as p on p.id = pod.product_id WHERE p.created_by = ".$shop->id." and p.type = 1 and pod.status = 0 and po.date=".date('Y-m-d')." order by po.id desc");
$array = Self::processData($data);
}else{
$array = array();
}
return sizeof($array);
}
public static function getTotalCompleteOrder(){
$shop = Shop::where('user_id',Auth::user()->id)->first();
if($shop){
$data = DB::select("SELECT po.*, pod.id as pod_id,pod.product_id,pod.color_id,pod.quantity,pod.price,pod.status as p_status,p.product_code,p.model,p.type FROM product_order as po RIGHT JOIN product_order_details as pod ON po.id = pod.order_id JOIN products as p on p.id = pod.product_id WHERE p.created_by = ".$shop->id." and p.type = 1 and pod.status = 1 order by po.id desc");
$array = Self::processData($data);
}else{
$array = array();
}
return sizeof($array);
}
public static function getTotalPendingOrder(){
$data = DB::select("SELECT po.*, pod.id as pod_id,pod.product_id,pod.color_id,pod.quantity,pod.price,pod.status as p_status,p.product_code,p.model,p.type FROM product_order as po RIGHT JOIN product_order_details as pod ON po.id = pod.order_id JOIN products as p on p.id = pod.product_id WHERE p.type = 1 and pod.status = 0 order by po.id desc");
$array = Self::processData($data);
return sizeof($array);
}
public static function getmonthlySale(){
$first_day_this_month = date('Y-m-01'); // hard-coded '01' for first day
$last_day_this_month = date('Y-m-t');
$total = 0;
$shop = Shop::where('user_id',Auth::user()->id)->first();
if($shop){
$data = DB::select("SELECT pod.quantity*pod.price as total FROM product_order as po RIGHT JOIN product_order_details as pod ON po.id = pod.order_id JOIN products as p on p.id = pod.product_id WHERE p.created_by = ".$shop->id." and p.type = 1 and pod.status = 1 and po.date between ".$first_day_this_month." and ".$last_day_this_month." order by po.id desc");
if(sizeof($data)>0){
foreach($data as $d){
$total +=$d->total;
}
}
}
return $total;
}
Error
add 'user_shops' to fillable model
exam:
protected $fillable = ['user_shops'];
or check if exists 'user_shops' in model?

Object of class Illuminate\Database\Eloquent\Collection could not be converted to int in laravel

I have a table named purchase_details in where during purchase, I am storing many items' purchase record at a time. During purchase also I am updating items table column opening_balance based on purchased items id, Now I am getting trouble when trying to sum 'purchase details' table quantity's value with 'items' table old opening_balance - in the controller, I am trying something like this-
public function store(Request $request)
{
$grandTotal = $request->input('grand_total');
$paidAmount = $request->input('paid_amount');
$purchase = new Purchase;
$purchase->no = $request->input('no');
$purchase->purchase_date = Carbon::parse($request->purchase_date)->format('Y-m-d');
$purchase->notes = $request->input('notes');
$purchase->supplier_id = $request->input('supplier');
$purchase->total_quantity = $request->input('total_quantity');
$purchase->grand_total = $grandTotal;
$purchase->paid_amount = $paidAmount;
$purchase->due_amount = abs($grandTotal - $paidAmount);
$purchase->save();
$itemDetails = [];
$itemIds = $request->input('itemIds');
$itemQuantities = $request->input('itemQuantities');
$itemPrices = $request->input('itemPrices');
$itemTotals = $request->input('itemTotals');
$orderNotes = $request->input('orderNotes');
foreach ($itemTotals as $key => $total) {
$itemDetails[] = [
'item_id' => $itemIds[$key],
'quantity' => $itemQuantities[$key],
'unit_price' => $itemPrices[$key],
'total_price' => $itemTotals[$key],
];
$openingBalance = Item::where('id', $itemIds[$key])->get(['opening_balance']);
DB::table('items')
->where('id', $itemIds[$key])
->update(['opening_balance' => $openingBalance + $itemQuantities[$key]]);
}
$purchase->purchaseDetails()->createMany($itemDetails);
return back();
}
You use collection as int, edit your code:
$openingBalance = Item::select(['opening_balance'])->where('id', $itemIds[$key])->first()->opening_balance;

Here customer A and Customer B message to one supplier,supplier click the Customer A messages,only open the particular customer A messages

Here customer A and Customer B message to one supplier, suppliers click the Customer A messages and wants to open only the particular customer A's messages not mix both of them. But I am getting the output with both messages from Customer A and Customer B. Please help me to solve this.
Model
[public function customer_to_supply() {
$this->db->select('*');
$this->db->from('communication');
$this->db->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = communication.supplier_id');
$this->db->join('customer_registration', 'communication.Customer_id=customer_registration.id');
//$this->db->join('communication', 'communication.product_id=contact_supplier.product_id');
$where = "communication.From' =>'customer'";
$this->db->where($where);
$query = $this->db->get();
$results = \[\];
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
}
controller
public function supplier_communication() {
$supp_id = $this->input->post('suppid');
$product_id = $this->input->post('proid');
$cust_id = $this->input->post('custid');
$this->session->userdata('cust',$cust_id);
$result1 = $this->Profile_model->fetch_Data($product_id);
$Userid = $this->session->userdata('id');
$result3 = $this->session->userdata('tt');
$data3 = array(
'message' => $this->input->post('messagee'),
'supplier_id' => $supp_id,
'product_id' => $product_id,
'Customer_id' => $cust_id,
'From' => $result3,
);
$this->Profile_model->data_insertt($data3);
redirect('welcome/messageview');
}
You have to pass the id of the customer ($customer_id) to your model function. Below is your function redesigned:
public function customer_to_supply($customerId) {
$qry = $this->db->select('*')
->from('communication')
->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = communication.supplier_id')
->join('customer_registration', 'communication.Customer_id=customer_registration.id')
->where('communication.From', 'customer')
->where('communication.Customer_id', $customerId)
->get();
if ($qry->num_rows() > 0)
return $qry->result_array();
return FALSE;
}

JSON data array query

i am using jsonTable to parse the data in to the Google table and it is working fine. now i have a problem to add multiple queries at the same time and display the data only in two columns of array which is already defined. here is my code:
$data = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table = array();
$table['cols'] = array(
array('label' => 'Vehicle', 'type' => 'number'),
array('label' => 'Distance Left', 'type' => 'number')
);
$rows = array();
while ($nt = mysql_fetch_array($data))
{
$temp = array();
$temp[] = array('v' => 'Nextoilchange');
$temp[] = array('v' =>$nt['Nextoilchange']);
// insert the temp array into $rows
$rows[]['c'] = $temp;
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
my first problem is this i want to add multiple queries in $data and each query gives one result. and my next problem is i want to display the data of multiple queries in above column defined as Distance left. and in vehicle column i want to add static data like above in $temp(1st row). i have searched a lot and i am confused how to do this. Please help me i want to display the table like this:
Vehicle Distance Left
nextoilchange 500
nextfilter 300
nextcheckup 400
I'm not tested this . If not not work try something like this .
<?php
$data[1] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$data[2] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table[1]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
$table[2]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
foreach($table as $key=>$eachtable)
{
$cols = $eachtable['cols'];
while ($nt = mysql_fetch_array($newdata))
{
foreach($cols as $key1=>$each_col)
{
if($each_col['label'] == $nt) //you have match the conditions
{
$row[$key1] = $nt['yourvalue'];
}
else
{
$row[$key1] = $nt['yourvalue1'];
}
$rows[] = $row;
}
}
$table[$key]['rows'] = $rows;
}
$jsonTable = json_encode($table);

Getting total rows using Drupal 7 Database API when using limit

I am using the Drupal 7 Database API to search my table. I am also using the paging and sorting extenders. So the problem is, how do I display the total number of records found when my query is using limit because of the pagination? Do I need to run my query that has all of the conditions TWICE? Once to get the count and another one with the limit? That seems inefficient. Here is my code for reference. I am new to the Database API so feel free to adjust my code or point me in the right direction if I'm doing something wrong. Also I'm not done with this yet and only have one condition in place, but I will end up having 3. THANKS:
function job_search() {
// Initialising output
$output = 'SOME STUFF';
// Table header
$header = array(
array('data' => 'Description'),
array('data' => 'Location', 'field' => 'job_location_display'),
array('data' => 'Specialty', 'field' => 'specialty_description'),
array('data' => 'Job Type', 'field' => 'job_board_type'),
array('data' => 'Job Number', 'field' => 'job_number'),
);
// Setting the sort conditions
if(isset($_GET['sort']) && isset($_GET['order'])) {
// Sort it Ascending or Descending?
if($_GET['sort'] == 'asc')
$sort = 'ASC';
else
$sort = 'DESC';
// Which column will be sorted
switch($_GET['order']) {
case 'Location':
$order = 'job_location_display';
break;
case 'Specialty':
$order = 'specialty_description';
break;
case 'Job Number':
$order = 'job_number';
break;
case 'Job Type':
$order = 'job_board_type';
break;
default:
$order = 'job_number';
}
}
else {
$sort = 'ASC';
$order = 'job_number';
}
// Query object
$query = db_select("jobs", "j");
// Adding fields
$query->fields('j');
if(isset($_GET['location'])) {
$query->condition('j.job_state_code', $_GET['location'], '=');
}
// Set order by
$query->orderBy($order, $sort);
// Pagination
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);
// Executing query
$result = $query->execute();
// Looping for filling the table rows
while($data = $result->fetchObject()) {
$description = '<div class="thumbnail"><img src="/sites/all/themes/zen/vista_assets/images/job_headers/' . $data->job_image_file . '"/></div>';
$description .= '<div class="title">' . $data->job_board_subtitle . '</div>';
// Adding the rows
$rows[] = array($description, $data->job_location_display, $data->specialty_description, $data->job_board_type, $data->job_number);
}
$output .= theme('pager');
// Setting the output of the field
$output .= theme_table(
array(
'header' => $header,
'rows' => $rows,
'attributes' => array('id' => array('job-listing')),
'sticky' => true,
'caption' => '',
'colgroups' => array(),
'empty' => t("No records found.")
)
).theme('pager');
// Returning the output
return $output;
}
This ended up working:
//get total records
$num_rows = $query->countQuery()->execute()->fetchField();
// add paging and sorting
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);
//execute again
$result = $query->execute();
According to the documentation:https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7
in order to get the total number of rows it is better to use db_query() function, cause it has the method rowCount() which returns total number of query rows:
<?php
// Using the same query from above...
$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));
// Fetch next row as a stdClass object.
$record = $result->fetchObject();
// Fetch next row as an associative array.
$record = $result->fetchAssoc();
// Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(1); // Grabs the title from the next row
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title');
// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// Also good to note that you can specify which two fields to use
// by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be nid => created
$result->fetchAllKeyed(1,0); // would be title => nid
// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($db_column_number);
// Count the number of rows
$result->rowCount();
?>