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());
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;
});
i have 1 million data using foreach.
ex table:
table
the data
data
i want to inserting that's data using batch/multipleinsert, but i have problem when i got duplicate data. if data duplicate i want the field amount will sum and update amount field with sum amount duplicated data.
this is my code before
<?php
foreach ($data_transaksi as $key)
{
if($key['STATUS_COA'] != $key['CHART_OF_ACCOUNT_STATUS'])
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2);
}
else
{
$amount = round($key['AMOUNT'],2) *-1;
}
}
else
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2)*-1;
}
else
{
$amount = round($key['AMOUNT'],2);
}
}
$dt_exsis = $this->ledger_model->cek_data_coa_exsis($key['COA_CODE'],$modul,$ID_USER);
if(empty($dt_exsis['id']))
{
//TRYINSERTINGBATCH
// $datainsert[] = '('.$key['COA_CODE'].','.$amount.','.$ID_USER.',"'.$modul.'")';
// $test = $key['COA_CODE'];
$datainput = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
$this->ledger_model->save_rows_to_table($datainput,'finance_lapkue_temp');
}
else
{
$amount_fix = $amount + $dt_exsis['AMOUNT'];
$data=array(
'AMOUNT' => $amount_fix
);
$this->ledger_model->edit_rows_to_table_where($data,'finance_lapkue_temp','id',$dt_exsis['id']);
// $q = "UPDATE finance_lapkue_temp set AMOUNT = '$amount_fix' where id = '".$dt_exsis['id']."'";
// $this->db->query($q);
}
// $data_amount[$key['COA_CODE']] += $amount;
}
?>
if i using this code, the proccess so slow
Good option will to pass only data to DB that you want to insert. All the data cleaning task can be done in controller.
// Create a data array and add all info
$data = [];
//if user does not exist add it in array
if (empty($dt_exist($id))) {
$data[$ID_USER] = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
}
else {
//if user exist in $data just modify the amount
if (!empty($data[$ID_USER])) {
$data[$ID_USER]['AMOUNT'] += $dt_exsis['AMOUNT'];
}
else {
// if user does not exist in data create add all info
$data[$dt_exsis['ID_USER']] = array(
'COA_CODE' => $dt_exsis['COA_CODE'],
'AMOUNT' => $dt_exsis['amount'],
'MODUL' => $dt_exsis['modul'],
'USER_ID' => $dt_exsis['ID_USER']
);
}
}
This will save multiple calls to DB and at the end you can pass $data and do multiple insert.
I need to create a drcode using the last insert id in the prescribed format,
previously I have used cor php to get the code but now in codeigniter am not able to get the code as the previous one. How can i do this? I am providing my controller and model
Controller
public function newdoctor_post() {
$employee_id = $this->post('EMPLOYEE_ID');
$doctorname = $this->post('DOCTOR_NAME');
$mobilenumber = $this->post('DRMOBILE');
$users_data = $this->Rest_user_model->doctor_exists($mobilenumber);
if ($users_data == 1) {
$message = ['status' => 2,
// 'result' => array(),
'message' => 'Doctor already registered'];
} else {
$speciality = $this->post('SPECIALITY');
$longitude = $this->post('LONGITUDE');
$latitude = $this->post('LATITUDE');
$drcode = $this->post('DRCODE');
$createdon = date('Y-m-d H:i:s');
$insert_array = array('EMPLOYEE_ID' => $employee_id, 'DOCTOR_NAME' => $doctorname, 'DRMOBILE' => $mobilenumber, 'SPECIALITY' => $speciality, 'LONGITUDE' => $longitude, 'LATITUDE' => $latitude, 'CREATEDON' => $createdon);
$users_data = $this->Rest_user_model->doctorregistration($insert_array);
$message = ['status' => 1, // 'result' => $users_data,
'message' => 'Doctor Registered Successfully'];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
Model
public function doctorregistration($data) {
if (!empty($data)) {
$this->db->insert('DOCTORDETAILS', $data);
return $this->db->insert_id();
}
return 0;
}
Code Generation
$sql1="SELECT DRCODE FROM DOCTORDETAILS ORDER BY DRCODEDESC LIMIT 1";
$query=mysql_query($sql1);
if (!$sql1) { // add this check.
die('Invalid query: ' . mysql_error());
}
$output_array2=array();
while($row=mysql_fetch_assoc($query))
{
$ids=$row['DRCODE'];
}
// echo $ids;
if($ids){
$su=1;
$num =$num = 'DR' . str_pad($su + substr($ids, 3), 6, '0', STR_PAD_LEFT);;
$unique=$num;
}else{
$unique='DR000001';
}
Try this - replace this code below with your Code Generation code.
$sql1="SELECT DRCODE FROM DOCTORDETAILS ORDER BY DRCODEDESC LIMIT 1";
$query=$this->db->query($sql1);
if (!$sql1) { // add this check.
die('Invalid query');
}
$output_array2=array();
foreach($query->result_array() as $row)
{
$ids=$row['DRCODE'];
}
// echo $ids;
if($ids){
$su=1;
$num =$num = 'DR' . str_pad($su + substr($ids, 3), 6, '0', STR_PAD_LEFT);;
$unique=$num;
}else{
$unique='DR000001';
}
You should make a different column fr drcode, leave it blank.
Now make a trigger on insert, it should be run after insert.
I am assuming DOCTORDETAILS as table name and drcode as column name
DELIMITER $$
CREATE TRIGGER trigger_after_insert
AFTER INSERT ON `DOCTORDETAILS` FOR EACH ROW
begin
UPDATE `DOCTORDETAILS` set drcode=CONCAT('DR',new.id);
END$$
DELIMITER ;
The trigger create a new string with your new auto generated id
Trigger in MySQL:
TechonTheNet
MySQL Trigger on after insert
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.
I have this pagination function abc and i want to pass this function to another functions elseif part and in that else if part i want to pass $data['books'] through the view... this is my controller and other function is in which i want to pass data of abc function is
public function abc($offset = 0){
$this->load->model('insert_model');
//$data ['query'] = $this->insert_model->view_data();
$this->load->library('table');
// Load Pagination
$this->load->library('pagination');
// Config setup
$config['base_url'] = base_url().'/welcome/';
$items= $config['total_rows'] = 20;
$perpage=$config['per_page'] = 1;
// I added this extra one to control the number of links to show up at each page.
$config['num_links'] = 5;
// Initialize
$this->pagination->initialize($config);
// Query the database and get results
// Here we add the limit and the offset
// The second parameter is the limit, since we are showing
// 10 per page, the limit should be 10
$data['books'] = $this->db->get('register',5, $offset);
// Create custom headers
$header = array('id','username','lastname','email' , 'password', 'image','status');
// Set the headings
$this->table->set_heading($header);
// Load the view and send the results
}
in the following function's elseif part i want to pass abc functions $data part inside view admin.. how can i pass it so that i can do pagination in that view
public function login_process()
{
$this->load->model('insert_model');
$data['users'] = array(
'fname' => $this->input->post('fname'),
'pass'=> $this->input->post('pass'),
);
$status= $this->insert_model->login_test($data);
$st['ss']=$this->insert_model->stat($data);
//print "<pre>"; print_r($status); die();
if($status == true && $st['ss'] [0] ['status'] == 0)
{
$ses = array(
'username' => $this->input->post('fname'),
'password' => $this->input->post('pass'),
);
$this->session->set_userdata($ses);
$im['pic']=$this->insert_model->image_fetc();
$this->load->view('header_view',$im);
$this->load->view('navside_view');
$this->load->view('user_view');
}
elseif($status == true && $st['ss']['0'] ['status'] == 1)
{
$ses = array(
'username' => $this->input->post('fname'),
'password' => $this->input->post('pass'),
);
$this->session->set_userdata($ses);
$im['pic']=$this->insert_model->image_fetc();
$this->abc();
$this->load->view('header_view',$im);
$this->load->view('navside_view');
$this->load->view('admin_view', $data);
}
else
{
$this->load->view('header_view');
$this->load->view('navside_view');
$this->load->view('center_view_login');
}
}
in my admin_view i am writing the following code and try to use the data which i have passed to admin view of function abc i.e $aaa code is:-
<?php echo $this->table->generate($books); ?>
<?php echo $this->pagination->create_links(); ?>
but there coming error undefined variable books and this books variable is defined in abc function whose data is passed through loginprocess elseif part in view admin view through $aaa variable please help me to sort it out
you can try this
public function abc($offset = 0, $status){
$this->load->model('insert_model');
//$data ['query'] = $this->insert_model->view_data();
$this->load->library('table');
// Load Pagination`enter code here`
$this->load->library('pagination');
// Config setup
$config['base_url'] = base_url().'/welcome/';
$items= $config['total_rows'] = 20;
$perpage=$config['per_page'] = 1;
// I added this extra one to control the number of links to show up at each page.
$config['num_links'] = 5;
// Initialize
$this->pagination->initialize($config);
// Query the database and get results
// Here we add the limit and the offset
// The second parameter is the limit, since we are showing
// 10 per page, the limit should be 10
$data['books'] = $this->db->get('register',5, $offset);
if($status){
return $data['books'];
}
// Create custom headers
$header = array('id','username','lastname','email' , 'password', 'image','status');
// Set the headings
$this->table->set_heading($header);
// Load the view and send the results
}
second function elseif part
elseif($status == true && $st['ss']['0'] ['status'] == 1)
{
$ses = array(
'username' => $this->input->post('fname'),
'password' => $this->input->post('pass'),
);
$this->session->set_userdata($ses);
$im['pic']=$this->insert_model->image_fetc();
$aaa = $this->abc(0,true);
$this->load->view('header_view',$im);
$this->load->view('navside_view');
$this->load->view('admin_view', $aaa);
}