Not inserting..Any Suggestions??
DB Driver: mysqli
using Codeigniter.
Controller
function add_quote()
{
$this->form_validation->set_rules('invoice_no', $this->lang->line("invoice_no"));
$this->form_validation->set_rules('date', $this->lang->line("date"), 'required');
$this->form_validation->set_rules('customer', $this->lang->line("customer"), 'required');
if($this->input->post('customer') == 'new') {
$this->form_validation->set_rules('state', $this->lang->line("state"));
$this->form_validation->set_rules('gstin', $this->lang->line("gstin"));
$this->form_validation->set_rules('company', $this->lang->line("company")." ".$this->lang->line("name"), 'required');
$this->form_validation->set_rules('email', $this->lang->line("customer")." ".$this->lang->line("email_address"), 'required|valid_email|is_unique[customers.email]');
$this->form_validation->set_rules('phone', $this->lang->line("phone"), 'required|min_length[6]|max_length[16]');
}
if ($this->form_validation->run() == true) {
print_r("helo World");
exit;
$form = $this->sales_model->process_form();
$customer_data = $form['customer_data'];
$products = $form['products'];
$data = $form['data'];
$dum = 'Q-'.$data['reference_no'];
$data['reference_no'] = $dum;
//unset($data['due_date'], $data['recurring']);
//echo '<pre />'; var_dump($data); var_dump($products); die();
}
//$data1 = array('reference_no' => 1);
//$this->db->insert('customers',$data1);
if ($this->form_validation->run() == true && $this->sales_model->addQuote($data, $products, $customer_data)) {
$this->session->set_flashdata('message', $this->lang->line("quote_added"));
redirect("sales/quotes");
} else {
$this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
$this->data['inv'] = false;
$this->data['q'] = true;
$this->data['customers'] = $this->sales_model->getAllCustomers();
$this->data['tax_rates'] = $this->sales_model->getAllTaxRates();
$this->data['companies'] = $this->sales_model->getAllCompanies();
$this->data['page_title'] = $this->lang->line("new_quote");
$this->page_construct('sales/add_quote', $this->data);
}
}
Model:
public function addQuote($data = array(), $items = array(), $customer = array()) {
if(!empty($customer)) {
if($this->db->insert('customers', $customer)) {
$customer_id = $this->db->insert_id();
}
$data['customer_id'] = $customer_id;
}
if($this->db->insert('quotes', $data)) { //Not inserted so Not enter into this loop
$quote_id = $this->db->insert_id();
foreach ($items as $item) {
$item['quote_id'] = $quote_id;
$this->db->insert('quote_items', $item);
}
return true;
}
else{
print_r("not inserted DATA");
exit;
}
return false;
}
Array Result:(Print_r($data))
Array ( [reference_no] => Q-SMGP/17-18/000003 [company_id] => 1
[company_name] => SMGP [vehicle_no] => dfg [date_time_supply] =>
2017-07-15 12:17 [place_supply] => sdafsd [consignee_name] => safsdaf
[consignee_address] => sdfsdaf [consignee_gstin] => 6556
[consignee_state] => sdfsa [consignee_state_code] => sdafaf [date] =>
2017-07-15 12:17 [due_date] => [expiry_date] => 2017-07-15 [user] => 1
[user_id] => 1 [customer_id] => 3 [customer_name] => Seed Arise
[total_tax] => 28.0000 [total] => 2100 [grand_total] => 2600.0000
[status] => ordered [shipping] => 500.00 [note] => )
Check if table fields name. Beasuse of wrong field name insert may be not working.
$this->db->last_query();
Use this to find. It will give you the sql query of insert. Run it in phpmyadmin.
Solution (28-02-2019):
As per CI Docs (Queries)
$this->db->insert('quotes');
print_r($this->db->error());
exit;
This will show if any error occurs else return an empty array.
On my case it shows invoice_no can't be null
Old:
function add_quote()
{
$this->form_validation->set_rules('invoice_no', $this->lang->line("invoice_no")); //This line is the Main problem...
$this->form_validation->set_rules('date', $this->lang->line("date"), 'required');
$this->form_validation->set_rules('customer', $this->lang->line("customer"), 'required');
if($this->input->post('customer') == 'new') {
$this->form_validation->set_rules('state', $this->lang->line("state"));
$this->form_validation->set_rules('gstin', $this->lang->line("gstin"));
$this->form_validation->set_rules('company', $this->lang->line("company")." ".$this->lang->line("name"), 'required');
$this->form_validation->set_rules('email', $this->lang->line("customer")." ".$this->lang->line("email_address"), 'required|valid_email|is_unique[customers.email]');
$this->form_validation->set_rules('phone', $this->lang->line("phone"), 'required|min_length[6]|max_length[16]');
}
$this->form_validation->set_rules('invoice_no',
$this->lang->line("invoice_no"));
Mistakenly I just included this line...And I removed REQUIRED option...So it shows no error and do nothing..So when I removed this line, It perfectly working..anyway Thankyou all
Try this way:
I have added two technique for quotes table insert query to check that data inserted or not.
public function addQuote($data, $items, $customer) {
if(!empty($customer)) {
if($this->db->insert('customers', $customer)) {
$customer_id = $this->db->insert_id();
}
$data['customer_id'] = $customer_id;
}
if(!empty($data)){
$this->db->insert('quotes', $data);
$quote_id = $this->db->insert_id();
// You can use one of this technique
//one is the last inserted id
// Second technique is described after this code
if($quote_id > 0){
foreach ($items as $single_item) {
$single_item['quote_id'] = $quote_id;
$this->db->insert('quote_items', $single_item);
}
return TRUE;
} else {
print_r("not inserted DATA");
exit;
}
}
return FALSE;
}
This the second technique of $this->db->affected_rows() to check quotes tabke inserted a row or not.
// OR Second, You can use affected rows
if($this->db->affected_rows() == '1'){
foreach ($items as $single_item) {
$single_item['quote_id'] = $quote_id;
$this->db->insert('quote_items', $single_item);
}
return TRUE;
}
I am assuming that you have taken all column name correctly.
Codeigniter has a log system to see what happing in the system you can use that here.
log_message('error', 'Last query executed you can write here regarding log message: '. print_r($this->db->last_query(), TRUE));
In order for the log file to actually be written, the logs/ directory must be writable. In addition, you must set the “threshold” for logging in application/config/config.php. You might, for example, only want error messages to be logged, and not the other two types. If you set it to zero logging will be disabled.
Related
I need to cache the results from Steam API parsing. And so the cached result lasts 15 minutes. I have a code:
public function load()
{
if (Auth::guest()) return response()->json(['success' => false, 'msg' => 'You need login!']);
$inventory = $this->getInventory(file_get_contents('http://steamcommunity.com/inventory/' . $this->user->steamid64 . '/570/2?l=russian&count=5000', true));
if (!$inventory) {
return response()->json(['success' => false, 'msg' => 'Error']);
}
$items = [];
$items_with_prices = json_decode(\Storage::get('prices.txt'));
$items_with_prices_by_key = [];
foreach ($items_with_prices->items as $item_price_key => $item_price_data) {
$items_with_prices_by_key[$item_price_key] = $item_price_data->price;
}
foreach ($inventory['rgInventory'] as $info) {
$item = $inventory['rgDescriptions'][$info['classid'] . '_' . $info['instanceid']];
if ($item['tradable'] == 0) continue;
$price = 0;//InventoryController::getItemPrice($item['market_hash_name']);
if (array_key_exists($item['market_hash_name'], $items_with_prices_by_key)) {
$price = $items_with_prices_by_key[$item['market_hash_name']];
}
if (!$price) continue;
if ($price < 1) $price = 0.64;
$type = $this->getType($item['type']);
$items[] = [
'id' => $info['id'],
'classid' => $item['icon_url'],
'price' => round($price, 2),
'type' => $type
];
}
usort($items, function($a, $b){
return ($b['price'] - $a['price']);
});
return response()->json(['success' => true, 'items' => $items]);
}
This code only works when a site user clicks on the "show my items" button and a request is sent to the list of user items in Steam Dota 2. Now if click constantly to get a list of items, Steam can block the server’s IP address for 24 hours. As I understand it, I need to throw the result of a $inventory variable into the cache. I create database table cache with fields id, user_id, items, date.
How can I now cache the result from a $inventory variable of 15 minutes?
Here is basic caching in laravel
$rememberTimeInSeconds = 3600;
$cachedResult = Cache::remember('name_of_your_cache', $rememberTimeInSeconds, function(){
// It can be any logic I just showing a simple query.
$users = User::all();
return $users;
});
So I'm having a bit of troubles with this query as it is the first time in which instead of checking for a value in a row, I'm checking if a row itself exists on database.
This is the problem that I'm facing:
UPDATE:
public function individualDiscountVerification($id){
// Get postID
$data['item'] = $this->PublicStore_model->readPostID($id);
$data['relationship'] = $this->PublicStore_model->getPostRelationship($id);
// Get Last Post ID
$postID = $id;
$activityTitle = $data['item']->title;
// Verify Data
$itemInCart = $this->PublicCart_model->verifyUserCartItem($postID);
// Redirect if row does not exist -- HERE IS WHERE I NEED HELP
if(!$itemInCart){
// Set message
$this->session->set_flashdata('error', 'You first need to add it to you cart');
// Redirect
redirect('store/read/'.$id);
// Redirect if seller is the same as the current userID
} elseif($this->session->userdata('user_id') == $data['relationship']->user_id) {
// Set message
$this->session->set_flashdata('error', 'You can not add discounts to your own products');
// Redirect
redirect('store/read/'.$id);
} else {
// Verify discount exists
$discount = $this->input->post('discount_code');
$discountCode = $this->PublicCart_model->verifySingleDiscount($discount);
if(!$discountCode){
// Set message
$this->session->set_flashdata('error', 'The discount has expired or is invalid');
// Redirect
redirect('store/read/'.$id);
} else {
// Get Last ID Data
$discountID = $discountCode->discount_id;
// Get Discount Type
$discountType = $this->PublicCart_model->getIndividualDiscountID($discountID);
// Verify data
$verifyItemDiscount = $this->PublicCart_model->verifySingleItemDiscountCode($postID, $discountID);
if($discountType->type == 'percent' && $verifyItemDiscount != NULL?:'' && $discountID == $data['relationship']->discount_id){
// Update Post Array
$postData = array(
'price' => round($data['relationship']->price * ((100 - $discountCode->amount) / 100), 2),
'discount_id' => $discountID,
);
// Update Post Array
$this->PublicCart_model->updateUserCartItem($postID, $postData);
// Set message
$this->session->set_flashdata('success', 'A percent discount type has been applied to your final price');
// Redirect
redirect('store/read/'.$data['item']->post_id);
} elseif($discountID != $data['relationship']->discount_id){
// Set message
$this->session->set_flashdata('error', 'Percent discount is not attached to this product');
// Redirect
redirect('store/read/'.$data['item']->post_id);
} elseif($discountType->type == 'float' && $verifyItemDiscount != NULL?:'' && $discountID == $data['relationship']->discount_id){
// Update Post Array
$originalprice = $data['relationship']->price;
$amount = $discountCode->amount;
$postData = array(
'price' => $originalprice - $amount,
'discount_id' => $discountID,
);
// Update Post Array
$this->PublicCart_model->updateUserCartItem($postID, $postData);
// Set message
$this->session->set_flashdata('success', 'A float discount type has been applied to your final price');
// Redirect
redirect('store/read/'.$data['item']->post_id);
} elseif($discountID != $data['relationship']->discount_id){
// Set message
$this->session->set_flashdata('error', 'Float discount is not attached to this product');
// Redirect
redirect('store/read/'.$data['item']->post_id);
}
// Activity Array
$activityData = array();
// Insert Activity
$this->Activity_model->add($activityData);
}
}
}
and here is the method in the model:
UPDATE:
/*
*
* IS IN USER'S CART? -- FROM HERE AND BELOW IS FOR THE INDIVIDUAL ITEMS DISCOUNT
*
*/
public function verifyUserCartItem($postID){
$query = $this->db->get($this->relationship, array(
'post_id' => $postID,
'friend_id' => $this->session->userdata('user_id'),
'type' => $this->cartType,
));
if($query->num_rows() > 0){
return $query->row_array();
} else {
return null;
}
}
/*
*
* DOES THE DISCOUNT EXISTS?; IF YES, WHAT TYPE OF DISCOUNT IT IS?
*
*/
public function verifySingleDiscount($discount){
$query = $this->db->get_where($this->discounts, array(
'code' => $discount,
));
return $query->row();
}
public function getIndividualDiscountID($discountID){
$query = $this->db->get_where($this->relationship, array(
'discount_id' => $discountID,
'status' => $this->published,
));
return $query->row();
}
/*
*
* IS THE DISCOUNT ATTACHED TO THE POST?; IF YES, UPDATE IT
*
*/
public function verifySingleItemDiscountCode($postID, $discountID){
$query = $this->db->get_where($this->relationship, array(
'post_id' => $postID,
'discount_id' => $discountID,
'status' => $this->published,
));
return $query->row();
}
public function updateUserCartItem($postID, $postData){
$this->db->select('*');
$this->db->where('friend_id', $this->session->userdata('user_id'));
$this->db->where('post_id', $postID);
$this->db->where('type', $this->cartType);
$this->db->update($this->relationship, $postData);
}
Note: As you can see I'm already using isset but that messes up the following blocks of code(I'll put the whole function if requested) which are not posted here; I already used if empty or if var === false but I'm still getting the same error.
try below in verifyUserCartItem function :
if($query->num_rows() > 0){
return $query->row_array();
} else {
return null;
}
and if(!$itemInCart){ instead of if(isset($itemInCart)){
For example:
var_dump($this->db->where('id', $id)->get('TABLE_NAME')->num_rows());
Hi all am trying to insert array of data to database using api in laravel .my task is i need to insert data from postman using some paramters(inputs)
when i run url the data is not inserting into database .
getting output status::true. am not getting any errors .how to solve this to insert data?
below is my code:
public function addToCart(){
$input = Input::all();
$data['status'] = 0;
$data['error'] = true;
// print_r($input);
$carty=array($input['cart']);
if(isset($input['user_id']) && isset($carty)> 0 ){
foreach($carty as $key => $val){
if(!empty($val['quantity']) && !empty($val['price']) && !empty($val['sku']) && !empty($val['qrcode']) && !empty($val['product_id']))
{
echo "here";
$totalPrice = $val['quantity']* $val['price'];
$cartId = [];
$cartId[] = DB::table('jocom_cart')->insertGetId(array(
'user_id' => $input['user_id'],
'product_id' => $val['product_id'],
'sku' => $val['sku'],
'quantity' => $val['quantity'],
'price' => $val['price'],
'total_price' => $totalPrice,
'qrcode' => $val['qrcode']
));
}
}
}
else{
$data['message'] = 'All field are required.';
}
return Response::json($data);
}
I saw some syntax errors in your posted code
$input = Input::all()
Must be (; missing)
$input = Input::all();
and
DB::table('jocom_cart')>insertGetId
must be (with ->, not >)
DB::table('jocom_cart')->insertGetId
Hope it's could resolved the problem
I am able to save associated records in cakephp3 but if you look at the code , the records are not saved all at once with 1 save call.
I did have a problem trying to save all the records at once. If you look at how its done you see the Guardian and Users table are save separately.
The code works and saves the records but saving all at once in 1 save call has been an issue as I got an error on the guardian table.
Guardians have a 1 to many relationship with students
Students and Users have a 1 to 1
Students to subjects and availabilityFotStudents both have a many to many
Code
public function add($gId=0) {
$this->loadModel("Guardians");
$this->loadModel('PaymentTypes');
$this->set("title","Add Student");
$guardians=null;
if ($gId>0){
$guardians =$this->Guardians->get($gId);
}
if ($this->request->is('post')) {
if ( $this->request->data['studenttype']==0){ //enquiry
$this->request->data['students']['address_billing'] = 0;
$this->request->data['students']['student_enq'] = 1;
}
else if ( $this->request->data['studenttype']==1){ //waitlist
$this->request->data['students']['address_billing'] = 1;
$this->request->data['students']['student_enq'] = 0;
}
else if ( $this->request->data['studenttype']==2){ //skip waitlist
$this->request->data['students']['address_billing'] = 4;
$this->request->data['students']['student_enq'] = 0;
}
if ( $this->request->data['students']['tutoring_typest_id']==1){
$this->request->data['students']['group_status']=0;
}
else if ( $this->request->data['students']['tutoring_typest_id']>1){
$this->request->data['students']['group_status']=1;
}
if ($this->request->data['students']['tutoring_typest_id']==3 ){//group only
$this->request->data['students']['address_billing'] = 4;
}
$data = $this->request->data;
// debug($data);
$uname= $this->request->data['Users']['username'];
if ($this->Students->Users->findByUsername($uname)->count()) {
$this->Flash->error(__('Username exists. Please, try again.'));
return $this->redirect(["action"=>"add",$gId]);
}
$userId=0;
$entity = $this->Students->Users->newEntity($this->request->data['Users'],['validate'=>false]);
$entity->role = "student";
$entity['role_id'] = 4;
$entity = $this->Students->Users->save($entity);
// debug( $entity);
$studentUserId = $entity->id;
if($guardians==null) {
$guardians = $this->Guardians->newEntity($this->request->data['guardians'], ['validate' => false]);
}
$guardianEntity = $this->Guardians->save($guardians);
$guardians = $this->Students->newEntity();
$studentData = $this->request->data['students'];
$studentData['subjects'] = $this->request->data['subjects'];
$studentData['availability_for_students'] = $this->request->data['availability_for_students'];
$studentEntity = $this->Students->patchEntity($guardians,$studentData,
[
"validate"=>false,
'associated' => [
"AvailabilityForStudents"=>["validate"=>false],
"Subjects"=>["validate"=>false]
]
]
);
$studentEntity->guardian_id = $guardianEntity->id;
$studentEntity->user_id = $studentUserId;
$studentEntity = $this->Students->save($studentEntity,
[
"validate"=>false,
'associated' => [
"AvailabilityForStudents"=>["validate"=>false],
"Subjects"=>["validate"=>false]
]
]
);
if ($studentEntity) {
$this->Flash->success(__('The student has been saved'));
return $this->redirect(["action"=>"index2"]);
} else {
$this->Flash->error(__('The student could not be saved. Please, try again.'),'flash_alert');
}
}//post
$subjects = $this->Students->Subjects->find('list', array( 'order' => array('Subjects.name' => 'asc') ));
$weekdays = $this->Students->weekDays;
$tutoringTypes = $this->Students->TutoringTypeStudents->find('list');
//$payments = $this->Student->paymentOptions;
$this->PaymentTypes->primaryKey("name");
$payments = $this->PaymentTypes->find( 'list', array(
'fields' => array('PaymentTypes.name','PaymentTypes.name')) );
$referrals = $this->Students->Referrals->find('list');
$tutorGender = $this->Students->Lessons->Tutors->tutorGender;
$this->set('guardians', $guardians);
$this->set(compact('referrals','subjects', 'tutoringTypes', 'weekdays','payments','tutorGender'));
}
you can use Tranactional data save. Where you can run multiple save method. if any save method failed then no data will be save. so it works like "1 save call" which you mentioned
I'm trying to prevent the user to create the same username. well my real problem is how to loop a list of data from model in controller. Maybe we know how to loop it in view by using this -> data['user'] and in view we can call $user. but how can we do that in controller layer.
here's my code
Controller
$username = strtolower($this->input->post('name'));
$fixUsername = str_replace(" ",".",$username);
$counter = 1;
$list[] = $this->addusermodel->getAllUsername();
for($i=0;$i<sizeof($list);$i++) {
if($list[$i] == $fixUsername) {
$counter = 0;
}
}
if($counter == 0) {
$data['result'] = "The username has already been taken";
$this->load->view('adduserview',$data);
} else {
$data = array(
'Nama' => $this->input->post('name'),
'Username' => $fixUsername."#praba",
'Password' => md5($this->input->post('password')),
'created' => date("Y-m-d h:i:sa"),
'createdBy' => $createdBy,
'lastModified' => date("Y-m-d h:i:sa"),
'lastModifiedBy' => $lastModifiedBy
);
$this->addusermodel->saveUser($data);
//$data['Username'] = $listName;
$data['message'] = "New user successfully added.";
$data['messageContent'] = "The username: ".$fixUsername."#praba". $counter;
$this->load->view('successpageview',$data);
//redirect('successpageview','refresh');
}
my model (is like usual)
function getAllUsername() {
$this->db->select('Username');
$this->db->from('tbluser');
$query = $this->db->get();
return $query->result_array();
}
I think a better approach would be to create another function in your model, which searches your database by ID, or by email, or by another unique field. If the function returns a row - then the user exists. If it returns nothing - then add a new user.