I want to insert data into my database. I am using codeigniter framework to build my app.
When I click on submit button,It don't give any error just reload the same page and data in not inserted in database.
Following my code to insert data into database -
public function addSale($saleDetails = array(), $items = array(), $warehouse_id)
{
foreach($items as $data){
$product_id = $data['product_id'];
$product_quantity = $data['quantity'];
$this->updateProductQuantity($product_id, $warehouse_id, $product_quantity);
}
// sale data
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
if($this->db->insert('sales', $saleData)) {
$sale_id = $this->db->insert_id();
$addOn = array('sale_id' => $sale_id);
end($addOn);
foreach ( $items as &$var ) {
$var = array_merge($addOn, $var);
}
if($this->db->insert_batch('sale_items', $items)) {
return true;
}
}
return false;
}
Based on https://ellislab.com/codeigniter/user-guide/database/examples.html , it seems to me, that you are missing a line -> $this->db->insert('sales', $saleData); . You do have it inside an if statement, but if statement will not execute it as a code, but check if it returns true.
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
$this->db->insert('sales', $saleData);
This should work. You can also check if it succeeds like this ->
return ($this->db->affected_rows() != 1) ? false : true;
Related
So I have website based on Laravel framework. I have table and the filter for table to filter the items - http://prntscr.com/ccht0f.
When I filter them by anything all works good, but when I change the page filtering disapers from session. http://prntscr.com/cchutt - http://prntscr.com/cchuyo. Looks like pagination destroys all sessions.
My code:
public function filters(Request $request)
{
$filter_item_acquisition_forms = [null];
$filter_collections = [null];
$filter_origin_dates = [null];
$order_by = request()->query('order_by', 'id');
$dir = request()->query('dir', 'desc');
$storage_items = StorageItem::with(
'authorClassification',
'placeClassification',
'classificationValueOrigin',
'classificationValueOriginDate',
'classificationValueItemAcquisitionForm',
'classificationValueCollection',
'classificationValuesMaterials',
'classificationValuesTechnique',
'employeeClassificationsRestorers',
'userLastUpdatedBy.employeeClassification',
'userResponsibleUser.employeeClassification',
'attachments'
);
$storage_items = $storage_items->id($request->filter_id)
->acceptanceId($request->filter_acceptance_id)
->acceptanceNumber($request->filter_acceptance_number)
->acceptanceDate($request->filter_acceptance_date)
->mainInventoryNumber($request->filter_main_inventory_number_from, $request->filter_main_inventory_number_to)
->scientificInventoryNumber($request->filter_scientific_inventory_number)
->imageInventoryNumber($request->filter_image_inventory_number)
->itemCosts($request->filter_item_costs_from, $request->filter_item_costs_to)
->originDate($request->filter_origin_date)
->updatedAt($request->filter_updated_at_from, $request->filter_updated_at_to)
->addingDate($request->filter_added_from, $request->filter_added_to)
->itemAcquisitionForm($request->filter_item_acquisition_form)
->collection($request->filter_collection)
->employee($request->filter_employee)
->isInExposition($request->filter_is_in_exposition)
->isRestored($request->filter_is_restored)
->haveAttachments($request->filter_have_attachments)
->haveNotCosts($request->filter_have_not_costs)
->searchInField($request->filter_search_in_field, $request->filter_word_or_phrase);
$storage_items = $storage_items->orderBy($order_by, $dir)->paginate(20);
foreach ($storage_items as $storage_item) {
if ($storage_item->classificationValueItemAcquisitionForm != null) {
$filter_item_acquisition_forms[$storage_item->classificationValueItemAcquisitionForm->id] = $storage_item->classificationValueItemAcquisitionForm->value;
}
if ($storage_item->classificationValueCollection != null) {
$filter_collections[$storage_item->classificationValueCollection->id] = $storage_item->classificationValueCollection->value;
}
if (!is_null($storage_item->classificationValueOriginDate)) {
$filter_origin_date[$storage_item->classificationValueOriginDate->id] = $storage_item->classificationValueOriginDate->value;
}
}
$request->flash();
return view('panel.storage_items.filters')->with([
'storage_items' => $storage_items,
'current_order_query' => compact('order_by', 'dir'),
'employees' => [null] + EmployeeClassification::lists('employee', 'id')->toArray(),
'filter_what_to_look_for' => [
'storage-items' => trans('fields.storage_items'),
'storage-item-acceptances' => trans('fields.storage_items_acceptances'),
'archive-objects' => trans('fields.archive_objects'),
'archive-documents' => trans('fields.archive_documents'),
'archive-docs-acceptance-acts' => trans('fields.archive_documents_acceptance_acts')
],
'filter_item_acquisition_forms' => $filter_item_acquisition_forms,
'filter_collections' => [null] + Classification::findOrFail(2)->classificationValues()->lists('value', 'id')->toArray(),
//'filter_collections' => $filter_collections,
'filter_origin_dates' => $filter_origin_dates,
'filter_search_in_field' => [
trans('fields.storage_items') => [
'item_name' => trans('fields.item_name'),
'author' => trans('fields.author'),
'about_the_author' => trans('fields.about_author'),
'item_description' => trans('fields.item_description'),
'content_description' => trans('fields.content_description'),
'item_history' => trans('fields.item_history'),
'branding_notes' => trans('fields.branding_notes'),
'damage_characteristics' => trans('fields.damage_characteristics'),
'published' => trans('fields.published'),
'exhibited' => trans('fields.exhibited'),
'inquiries' => trans('fields.inquiries')
],
trans_choice('fields.attachments', 0) => [
'attachment_name' => trans('fields.name'),
'attachment_description' => trans('fields.description')
]
]
]);
}
So I fixed it myself.
Solution:
I got the collection ID from request and stored it in variable.
$filter_collection = $request->filter_collection;
Passed variable to the view
->with('filter_collection', $filter_collection)
And changed my pagination to pass collection ID to next page
{{ $storage_items->appends(['filter_collection' => $filter_collection])->links() }}
I'm running the following code. if the record already exists it overrides the existing fields with the new one at $updated_fields_array. But if the record doesn't exist I don't know how to add a new record with new fields ($new_fields_array). which operator should I use? Can someone help me out?
$current_time = time();
$current_mongo_date = new MongoDate($current_time);
$collection = $this->mongo->selectCollection(MONGO_NOTIFY_DB, 'AccountSettings');
$criteria_array=array("email" => $email, "name" => $name);
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'updated' => $current_mongo_date,
'email' => $email,
'name' => $name,
'last_sent' => $current_time,
'deleted' => FALSE
);
try {
$collection->update(
$criteria_array,
array('$set' => $updated_fields_array),
array("upsert" => true)
);
} catch (MongoCursorException $mce) {
log_message('error', 'QUERY UPDATE FAILED :: AccountSettings :: ' . print_r($updated_fields_array, true) . ' :: ' . $mce->getMessage());
}
return;
Evgeny's Answer is ok but you are missing one problem
You have duplicate keys in the updated_fields_array and new_fields_array which throws MongoDB WriteException because Mongo will first create the new object and only then update it.
so change
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'updated' => $current_mongo_date,
'email' => $email,
'name' => $name,
'last_sent' => $current_time,
'deleted' => FALSE
);
to
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'email' => $email,
'name' => $name,
'deleted' => FALSE
);
and change the query (as Evgeny wrote or the Documentation)
$collection->update(
$criteria_array,
array('$set' => $updated_fields_array, '$setOnInsert'=> $new_fields_array),
array("upsert" => true)
);
You can use UPDATE command with upsert option and $set/$setOnInsert operators (see https://docs.mongodb.org/manual/reference/operator/update/setOnInsert/). See example below (note, that you should have unique index on {email:1,name:1})
$current_time = time();
$current_mongo_date = new MongoDate($current_time);
$collection = $this->mongo->selectCollection(MONGO_NOTIFY_DB, 'AccountSettings');
$criteria_array=array("email" => $email, "name" => $name);
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'deleted' => FALSE
);
try {
$collection->update(
$criteria_array,
array('$set' => $updated_fields_array, '$setOnInsert'=> $new_fields_array),
array("upsert" => true)
);
} catch (MongoCursorException $mce) {
log_message('error', 'QUERY UPDATE FAILED :: AccountSettings :: ' . print_r($updated_fields_array, true) . ' :: ' . $mce->getMessage());
}
return;
I had to use updateOne
$result = $collection->updateOne(
array('first_id' => 123456,'some_number' => 333333),
array('$set' => array('some_status' => 'Delayed')),
array('upsert' => true)
);
I have no idea why this keeps returning false.
The best part is at the echo statements it actually echo's. This function is in a plugin that I am writing for WordPress.
function find_field($field_name,$array) {
if(array_key_exists($field_name,$array)) {
echo 'Here';
echo $array[$field_name];
return $array[$field_name];
}
foreach($array as $value) {
if(is_array($value)) {
find_field($field_name,$value);
}
}
return false;
}
If I run this: echo find_field('cellphone_number',$arr);
And this is my $arr:
array(
'page' => 'wp_crm_add_new',
'wp_crm' => array(
'user_data' => array(
'user_id' => array(
(int) 0 => array(
'value' => ''
)
),
'user_pass' => array(
(int) 1428 => array(
'value' => ''
)
),
'role' => array(
(int) 2718 => array(
'value' => ''
)
),
'display_name' => array(
(int) 14454 => array(
'value' => 'Albert'
)
),
'user_email' => array(
(int) 26059 => array(
'value' => 'albert#domain.com'
)
),
'company' => array(
(int) 85772 => array(
'value' => ''
)
),
'cellphone_number' => array(
(int) 62506 => array(
'value' => '0820000000'
)
),
'last_visit' => array(
(int) 45073 => array(
'value' => ''
)
)
)
),
'meta-box-order-nonce' => '1374268beb',
'closedpostboxesnonce' => '92fffdd685',
'wp_crm_update_user' => '42d35393d7',
'show_admin_bar_front' => 'false',
'color-nonce' => 'c02f4b0a88',
'admin_color' => 'sunrise',
'original_publish' => 'Publish',
'publish' => 'Save'
)
I get false as the result, every time. What am I doing wrong?
This is happening because you return false. Here's the logic break-down:
function find_field($field_name,$array) {
if(SOMETHING) {
DO SOMETHING
return SOMETHING;
}
foreach($array as $value) {
if(SOMETHING) {
CALL RECURSIVE FUNCTION
}
}
return false;
}
Put like this... if you call the function at any point and send a value that passes the first if statement, then you return a value. If you do not pass that if statement (aka the array_key doesn't exist) then you move into a foreach loop, which does some stuff, calls a recursive function which eventually returns a value (and does nothing with it) before moving on to the final line of code... return false.
It is important to first think of a recursive function as a one-time function before compounding it into a recursive one.
Just like any other function, this recursive function is going to execute every line of code (although interrupted) before it is done. The last line of code you execute is always a "return false" which is throwing your result.
Perhaps you should be returning the inner foreach loop value when you call the recursive function:
function find_field($field_name,$array) {
if(array_key_exists($field_name,$array)) {
echo 'Here';
echo $array[$field_name];
return $array[$field_name];
}
foreach($array as $value) {
if(is_array($value)) {
return find_field($field_name,$value);
}
}
return false;
}
when I insert an array in the db, I get the error "unidentified index" in some of the variables even though they all have their corresponding values. Tried using print_r, and it returned an array with values, but when I try to insert the array, the values become null. I dont understand why and I can't see the error in my code.
here's my controller
public function test()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$user_id = $session_data['user_id'];
$table_id = $this->input->post('table');
$start = $this->input->post('start');
$end = $this->input->post('end');
$query = $this->process_resto_list->test($table_id);
if ($query->num_rows() > 0)
{
$row = $query->row();
$resto_id = $row->resto_id;
$table_number= $row->table_number;
$table_size = $row->table_size;
}
//$resto_id = $session_data['user_id'];
$values = array(
'resto_id' => $resto_id,
'diner_id' => $user_id,
'date' => $this->input->post('date'),
'start_time' => $start,
'end_time' => $end,
'table_number' => $table_number,
'number_of_people' => $table_size,
);
if($this->process_resto_list->insert_reservation($values))
redirect('reservation_test/reservation', 'location');
//print_r($values);
}
Here's my model
public function insert_reservation($values)
{
date_default_timezone_set("Asia/Manila");
$data = array(
'resto_id' => $values['resto_id'],
'diner_id' => $values['user_id'],
'date' => date('Y-m-d'),
'start_time' => $values['start'],
'end_time' => $values['end'],
'table_number' => $values['table_number'],
'number_of_people' => $values['table_size'],
);
return $this->db->insert('resto_reservations', $data);
}
When using print_r here's the result of the array
Array ( [resto_id] => 9 [diner_id] => 14 [date] => [start_time] => 11:00 [end_time] => 13:00 [table_number] => 6 [number_of_people] => 4 )
Please help me point out the error. Thank you
In your model. Change values as follows
$data = array(
'resto_id' => $values['resto_id'],
'diner_id' => $values['diner_id'],
'date' => date('Y-m-d'),
'start_time' => $values['start_time'],
'end_time' => $values['end_time'],
'table_number' => $values['table_number'],
'number_of_people' => $values['number_of_people'],
);
I just replaced my model with this. Thanks everyone!
$data = array(
'resto_id' => $values['resto_id'],
'diner_id' => $values['diner_id'],
'date' => date('Y-m-d'),
'start_time' => $values['start_time'],
'end_time' => $values['end_time'],
'table_number' => $values['table_number'],
'number_of_people' => $values['number_of_people'],
);
I tried doing the following and surprisingly it only populates the first table (new_guest) while writing only zero values to the other (new_reservation). How can I properly configure this?
Controller:
function guest_checks_in() {
$data_guest = array (
'guest_title' => $this->input->post('guest_title'),
'guest_name' => $this->input->post('guest_name'),
'guest_gender' => $this->input->post('guest_gender'),
'guest_phone' => $this->input->post('guest_phone'),
'guest_email' => $this->input->post('guest_email'),
'guest_address' => $this->input->post('guest_address'),
'guest_province' => $this->input->post('guest_province'),
'guest_country' => $this->input->post('guest_country'),
'guest_postal_code' => $this->input->post('guest_postal_code'),
'guest_dob' => $this->input->post('guest_dob'),
'guest_nic_pp_dl' => $this->input->post('guest_nic_pp_dl')
);
$data_reservation = array (
'room_type' => $this->input->post('room_type'),
'meal_type' => $this->input->post('meal_type'),
'bed_type' => $this->input->post('bed_type'),
'ext_beds' => $this->input->post('ext_beds'),
'number_of_guests' => $this->input->post('number_of_guests'),
'start_date' => $this->input->post('start_date'),
'end_date' => $this->input->post('end_date'),
'reservation_duration' => $this->input->post('reservation_duration'),
'room_number' => $this->input->post('room_number'),
'total' => $this->input->post('total')
);
$this->reservations_model->add_guests($data_guest);
$this->reservations_model->add_reservations($data_reservation);
$this->confirm_check_in();
}
Model:
class Reservations_model extends CI_Model {
function add_guests($data_guest) {
$this->db->insert('new_guest', $data_guest);
return;
}
function add_reservations($data_reservation) {
$this->db->insert('new_reservation', $data_reservation);
return;
}
}
it will be good if you use transaction. if data in both tables must be entered.
function guest_checks_in() {
$data_guest = array (
'guest_title' => $this->input->post('guest_title'),
'guest_name' => $this->input->post('guest_name'),
'guest_gender' => $this->input->post('guest_gender'),
'guest_phone' => $this->input->post('guest_phone'),
'guest_email' => $this->input->post('guest_email'),
'guest_address' => $this->input->post('guest_address'),
'guest_province' => $this->input->post('guest_province'),
'guest_country' => $this->input->post('guest_country'),
'guest_postal_code' => $this->input->post('guest_postal_code'),
'guest_dob' => $this->input->post('guest_dob'),
'guest_nic_pp_dl' => $this->input->post('guest_nic_pp_dl')
);
$data_reservation = array (
'room_type' => $this->input->post('room_type'),
'meal_type' => $this->input->post('meal_type'),
'bed_type' => $this->input->post('bed_type'),
'ext_beds' => $this->input->post('ext_beds'),
'number_of_guests' => $this->input->post('number_of_guests'),
'start_date' => $this->input->post('start_date'),
'end_date' => $this->input->post('end_date'),
'reservation_duration' => $this->input->post('reservation_duration'),
'room_number' => $this->input->post('room_number'),
'total' => $this->input->post('total')
);
$this->reservations_model->add_all_guests($data_guest,$data_reservation);
$this->confirm_check_in();
}
in model
function add_all_guests($data_guest,$data_reservation) {
$this->db->trans_begin();
$this->db->insert('new_guest', $data_guest);
$this->db->insert('new_reservation', $data_reservation);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return false;
}
else
{
$this->db->trans_commit();
return true;
}
}