I currently writing an sms system for the end user. however, When I do the testing on the function i encounter sms credit deduction error.
There are three table in this function which are company, user and transaction.
I did many testing on this function. just cant get the credit deduction correctly.
for example there are 1000 credit in each table.
Initial value
company.sms_bal = 1000
user.user_credit_bal= 1000
transaction.transaction_balance = 1000
testing #1
deduct 1 credit on each table. it deducts correctly.
company.sms_bal = 999
user.user_credit_bal= 999
transaction.transaction_balance = 999
testing #2
deduct 2 credit on each table. it deducts incorrectly,
company.sms_bal = 997
user.user_credit_bal= 997
transaction.transaction_balance = 998 suppose to be 997.
P/S it does not always deduct incorrectly, just sometimes. Please kindly advice me. However if you are unsure my question just let me know I am willing to assist you.
Below is the function for your reference
function process_send_sms($data){
global $CONF, $Q, $OUT, $DB, $DBSH, $CODE, $LANG;
//
// check credit
//
$check_credit = check_credit($data);
if($check_credit['status'] == '100'){
//
// check credit and update credit and update track
//
// get $company_credit_bal
$DBSH->u_select('company', $company_data, array(
'company_id' => $company_id,
));
$company_credit_bal = $company_data['sms_bal'];
// get $user_credit_bal
$DBSH->u_select('user', $user_data, array(
'user_id' => $user_id,
));
$user_credit_bal = trim($user_data['user_credit_bal']);
$number_bulk_mt = trim($total_credit);
//
// update company
//
$rows = $DBSH->update(array(
'table' => 'company',
'set' => array(array('sms_bal = ?', $company_credit_bal - $number_bulk_mt),),
'where' => array(array('company_id = ?', $company_id),),));
$rows = $DBSH->update(array(
'table' => 'user',
'set' => array(array('user_credit_bal = ?', $user_credit_bal - $number_bulk_mt),),
'where' => array(array('user_id = ?', $user_id),),));
}else{
$return_data['error'] = $check_credit['error'];
}
if($check_credit['status'] == '100'){
//
// insert to the track
//
$arr = debug_backtrace();
$function_name = $arr[0]["function"];
$data = array(
'no_phones' => $total_credit,
'company_id' => $company_id,
'user_id' => $user_id,
'msg_type' => $function_name,
'track_mt_create_time' => $timestr,
'track_mt_update_date' => $timestr,
);
$DBSH->u_insert('bulk_mt_log_track', $data);
$ref_id = $DBSH->u_lastid('bulk_mt_log_track');
if($sendsmscsv == 'Y'){
foreach($phone_tem as $k => $v){
$phone_no = $v['phone'];
$message = $v['message'];
$coding = 1;
if($v['lang'] == '2'){
$coding = 3;
}
$check_credit = $credit_class->check_per_credit($phone_no,$is_intern);
$send_c_code = $check_credit['c_code' ];
$per_credit = $check_credit['per_credit'];
if($phone_no){
do{
$msgid = session_get()."_".$user_id;
$check_valid === false;
$found = $DBSH->u_count('bulk_mt_log_data', array(
'msgid' => $msgid,
));
if(!$found){
$check_valid === true;
}
$found = $DBSH->u_count('bulk_mt_log', array(
'msgid' => $msgid,));
if(!$found){
$check_valid === true;
}
}while($check_valid === false);
//
// Perform merge sms
//
$message = process_message_merge($phone_no,$user_id,$message,$company_id);
if($coding == '3'){
$len = mb_strlen($message, 'UTF-8');
$arr = array();
for( $i=0; $i<$len; $i++){
$arr[] = mb_substr($message,$i,1,'UTF-8');;
}
$message2="";
foreach($arr as $k => $substr){
$message2 .= uniord($substr);
}
$message = $message2;
}
else{
$coding = 0;
}
$data = array(
'bulk_mt_log_id' => null,
'user_id' => $user_id,
'company_id' => $company_id,
'mt_to' => $phone_no,
'campaign' => $campaign_name,
'mt_status' => 'P',
'mt_text' => $message,
'coding' => $coding,
'msgid' => $msgid,
'is_intern' => $is_intern?$is_intern:'NOT',
'per_credit' => $per_credit ? $per_credit:'0',
'mt_from' => $mt_from?$mt_from:'',
'send_c_code' => $send_c_code,
'mt_create_date' => $timestr,
'mt_update_date' => $timestr,
'ref_id' => $ref_id,
'gateway_id' => $gateway_id,
);
$DBSH->u_insert('bulk_mt_log', $data);
$rows = $DBSH->select(array(
'field' => array('*'),
'table' => 'transaction',
'where' => array(array('company_id = ?', $company_id),
array('transaction_balance > ?', 0),
array('transaction_sms_expire_date > ?', $timestr),),
'order' => 'transaction_sms_expire_date ASC',
));
$data_transaction_id = array();
while($row = $DBSH->fetchRow(DB_FETCHMODE_ASSOC)){
$data_transaction_id[] = $row[transaction_id];
}
$transaction_id = $data_transaction_id[0];
if($transaction_id){
$rows = $DBSH->update(array(
'table' => 'transaction',
'set' => array(array('transaction_balance = transaction_balance - '.$per_credit),),
'where' => array(array('company_id = ?', $company_id),
array('transaction_id = ?', $transaction_id),),
));
}
}
}
}else{
if ($phone){
foreach($phone as $k => $phone_no){
foreach($sms_message as $km => $message){
$check_credit = $credit_class->check_per_credit($phone_no,$is_intern);
$send_c_code = $check_credit['c_code' ];
$per_credit = $check_credit['per_credit'];
if($phone_no){
do{
$msgid = session_get()."_".$user_id;
$check_valid === false;
$found = $DBSH->u_count('bulk_mt_log_data', array(
'msgid' => $msgid,
));
if(!$found){
$check_valid === true;
}
$found = $DBSH->u_count('bulk_mt_log', array(
'msgid' => $msgid,));
if(!$found){
$check_valid === true;
}
}while($check_valid === false);
//
// Perform merge sms
//
$message = process_message_merge($phone_no,$user_id,$message,$company_id);
if($message_type == 'unicode'){
$coding = 3;
$len = mb_strlen($message, 'UTF-8');
$arr = array();
for( $i=0; $i<$len; $i++){
$arr[] = mb_substr($message,$i,1,'UTF-8');;
}
$message2="";
foreach($arr as $k => $substr){
$message2 .= uniord($substr);
}
$message = $message2;
}
else{
$coding = 0;
}
$data = array(
'bulk_mt_log_id' => null,
'user_id' => $user_id,
'company_id' => $company_id,
'mt_to' => $phone_no,
'campaign' => $campaign_name,
'mt_status' => 'P',
'mt_text' => $message,
'coding' => $coding,
'msgid' => $msgid,
'is_intern' => $is_intern?$is_intern:'NOT',
'per_credit' => $per_credit ? $per_credit:'0',
'send_c_code' => $send_c_code,
'mt_create_date' => $timestr,
'mt_update_date' => $timestr,
'ref_id' => $ref_id,
'mt_from' => $mt_from?$mt_from:'',
'gateway_id' => $gateway_id,
);
$DBSH->u_insert('bulk_mt_log', $data);
$rows = $DBSH->select(array(
'field' => array('*'),
'table' => 'transaction',
'where' => array(array('company_id = ?', $company_id),
array('transaction_balance > ?', 0),
array('transaction_sms_expire_date > ?', $timestr),
),
'order' => 'transaction_sms_expire_date ASC',
));
$data_transaction_id = array();
while($row = $DBSH->fetchRow(DB_FETCHMODE_ASSOC)){
$data_transaction_id[] = $row[transaction_id];
}
$transaction_id = $data_transaction_id[0];
if($transaction_id){
$rows = $DBSH->update(array(
'table' => 'transaction',
'set' => array(array('transaction_balance = transaction_balance - '.$per_credit),),
'where' => array(array('company_id = ?', $company_id),
array('transaction_id = ?', $transaction_id),),
));
}
}
}
}
}
}
}else{
$return_data['error'] = $check_credit['error'];
}
if($return_data){
$return_data['status'] ='102';
}else{
$return_data['status'] ='100';
}
return $return_data;
}
Related
Hello I have an array and I'm looping through it using for loop and inside for loop, there is switch cases I don't know why my code is running even if switch condition is not fulfilled
Here is my code:
for($j=0;$j<count($fees_type_arr);$j++){
$month = "N/A";
switch ($fees_type_arr[$j]) {
case 'adm':
$sql_record_data = array(
'tid' => $tid.$j+1,
'slip_no' => $slip_no,
'date_time' => $current_date_time,
'uid' => $uid,
'month' => $month,
'amount' => $admission_fees,
'fees_type' => 'adm'
);
if($wpdb->insert($record_table, $sql_record_data)){
$ok = 1;
}
else{
$ok = 0;
throw new Exception($wpdb->print_error());
}
break;
case "trn":
$sql_record_data = array(
'tid' => $tid.$j+1,
'slip_no' => $slip_no,
'date_time' => $current_date_time,
'uid' => $uid,
'month' => $month,
'amount' => $transport_chg,
'fees_type' => 'trn'
);
if($wpdb->insert($record_table, $sql_record_data)){
$ok = 1;
}
else{
$ok = 0;
throw new Exception($wpdb->print_error());
}
break;
case "ann":
$sql_record_data = array(
'tid' => $tid.$j+1,
'slip_no' => $slip_no,
'date_time' => $current_date_time,
'uid' => $uid,
'month' => $month,
'amount' => $annual_chg,
'fees_type' => 'ann'
);
if($wpdb->insert($record_table, $sql_record_data)){
$ok = 1;
}
else{
$ok = 0;
throw new Exception($wpdb->print_error());
}
break;
case "rec":
$sql_record_data = array(
'tid' => $tid.$j+1,
'slip_no' => $slip_no,
'date_time' => $current_date_time,
'uid' => $uid,
'month' => $month,
'amount' => $recreation_chg,
'fees_type' => 'rec'
);
if($wpdb->insert($record_table, $sql_record_data)){
$ok = 1;
}
else{
$ok = 0;
throw new Exception($wpdb->print_error());
}
break;
}
}
Here is my array
$fees_type_arr = array("adm","ttn","trn","ann","rec");
tid is the primary key and I'm getting an error Duplicate entry for primary key which is due to the code inside 1st case i.e case "adm" is running multiple times
When you do $j+1 in your code it overrides the value of $j and again set it back to 1. So each time your loop will call the first case which is "adm". You need to store the real value of $j and assign it back in the end. Use this code.
for($j=0;$j<count($fees_type_arr);$j++){
$month = "N/A";
$oldj = $j;
switch ($fees_type_arr[$j]) {
case 'adm':
$sql_record_data = array(
'tid' => $tid.$j+1,
'slip_no' => $slip_no,
'date_time' => $current_date_time,
'uid' => $uid,
'month' => $month,
'amount' => $admission_fees,
'fees_type' => 'adm'
);
if($wpdb->insert($record_table, $sql_record_data)){
$ok = 1;
}
else{
$ok = 0;
throw new Exception($wpdb->print_error());
}
break;
case "trn":
$sql_record_data = array(
'tid' => $tid.$j+1,
'slip_no' => $slip_no,
'date_time' => $current_date_time,
'uid' => $uid,
'month' => $month,
'amount' => $transport_chg,
'fees_type' => 'trn'
);
if($wpdb->insert($record_table, $sql_record_data)){
$ok = 1;
}
else{
$ok = 0;
throw new Exception($wpdb->print_error());
}
break;
case "ann":
$sql_record_data = array(
'tid' => $tid.$j+1,
'slip_no' => $slip_no,
'date_time' => $current_date_time,
'uid' => $uid,
'month' => $month,
'amount' => $annual_chg,
'fees_type' => 'ann'
);
if($wpdb->insert($record_table, $sql_record_data)){
$ok = 1;
}
else{
$ok = 0;
throw new Exception($wpdb->print_error());
}
break;
case "rec":
$sql_record_data = array(
'tid' => $tid.$j+1,
'slip_no' => $slip_no,
'date_time' => $current_date_time,
'uid' => $uid,
'month' => $month,
'amount' => $recreation_chg,
'fees_type' => 'rec'
);
if($wpdb->insert($record_table, $sql_record_data)){
$ok = 1;
}
else{
$ok = 0;
throw new Exception($wpdb->print_error());
}
break;
}
$j = $oldj;
}
It will reassign the real value to $j and will work perfectly!!
Your variable $tid seems like a string. So even if $j is an incremental integer, $tid.$j+1 will result as 1.
You can change that to $tid.($j+1) (adding brackets).
Example :
<?php
$tid = 'test';
$j = 10;
echo $tid.$j+1;
// returns 1
?>
After change :
<?php
$tid = 'test';
$j = 10;
echo $tid.($j+1);
// returns 'test11'
?>
Just on a lighter note, it seems like there is a lot of repetitive code in the example you have submitted, you can move it to a function or more dynamic looping to avoid code duplication.
I am currently working on adding multiple requests in single click using CodeIgniters insert_batch.
This is my model
function add_request($data) {
$this->db->insert_batch('requests',$data);
}
This is my controller
if($_POST) {
$code = $this->input->post('code');
$about = $this->input->post('about');
$qnty = $this->input->post('quantity');
$budget = $this->input->post('budget');
$sched = $this->input->post('sched');
for($i = 0; $i < count($code); $i++) {
$data[$i] = array(
'code' => $code,
'description' => $_POST['desc'],
'qnty' => $qnty,
'budget' => $budget,
'sched' => $sched,
'from' => $this->session->userdata('user_id'),
'status' => 'Pending',
'about' => $about
);
$this->request->add_request($data[$i]);
}
This code doesnt work It only adds blank record.
Consider this code for the controller:
$data = array();
for($i = 0; $i < count($code); $i++) {//build the array
$data[$i] = array(
'code' => $code,
'description' => $_POST['desc'],
'qnty' => $qnty,
'budget' => $budget,
'sched' => $sched,
'from' => $this->session->userdata('user_id'),
'status' => 'Pending',
'about' => $about
);
}
//$data will be a bidimentional array
//pass $data to the model after the looping is done, thus the array is complete
$this->request->add_request($data);
here i m doing a json_encode
public function get_posts_for_category($user_id,$category_id,$page)
{
$cat_id = $this->ApiModel->get_category_id($category_id);
$total_row = $this->ApiModel->get_category_posts_count($cat_id->category);
$per_page = 2;
$total_pages = $total_row / $per_page;
$posts = $this->ApiModel->get_category_posts($cat_id->category,$per_page,$page);
$data = array();
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id,$post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp);
$data[] = array('page' => $page, 'posts' => $array, 'is_favorite' => $status);
}
echo strip_tags(json_encode($data));
}
the output i m getting from the above code is
But i want some thing like this
<?php
public function get_posts_for_category($user_id,$category_id,$page)
{
$cat_id = $this->ApiModel->get_category_id($category_id);
$total_row = $this->ApiModel->get_category_posts_count($cat_id->category);
$per_page = 2;
$total_pages = $total_row / $per_page;
$posts = $this->ApiModel->get_category_posts($cat_id->category,$per_page,$page);
$data = array();
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id,$post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp, 'is_favorite' => $status);
$data[] = array('page' => $page, 'posts' => $array, 'total_posts' => count($posts), 'total_pages' => $total_pages);
}
echo strip_tags(json_encode($data));
}
?>
$return = array(
'page' => $page,
'total_posts' => $total_row,
'total_page' => $total_pages,
);
$data = [];
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id, $post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp, 'is_favorite' => $status);
$data[] = $array;
}
$return['posts'] = $data;
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($return));
just replace this code with your foreach & echo statement.
You never should use strip_tags in conjunction with json_encode because you are already encoding the data it's receivers choice to do whatever he wants also in this process you might break the encoding.
Also you should use CI output library to send response you must not echo anything from your controller. see here https://ellislab.com/codeigniter/user-guide/libraries/output.html for more details
If you would like the numeric values to be output as such, (instead of strings) you may wish to try:
json_encode($return, JSON_NUMERIC_CHECK);
To format the outputted JSON nicely (indentation etc) use:
json_encode($return, JSON_PRETTY_PRINT);
You can use various combinations of the above as per json_encode's options.
As for the boolean values (instead of "true" and "false" returned as strings), you'll need to cast them as boolean types first:
$status = (bool) true;
i got this model which inserts data on the database but the problem is, other fields are not required so i did this,
public function insert(){
if($this->input->post('MNAME') = NULL){
$mname = "n/a";
}else{
$mname = $this->input->post('MNAME');
}
if($this->input->post('EXTENSION') = NULL){
$ext = "n/a";
}else{
$ext = $this->input->post('EXTENSION');
}
if($this->input->post('EMAIL') = NULL){
$email = "n/a";
}else{
$email = $this->input->post('EMAIL');
}
if($this->input->post('CELLNO') = NULL){
$cell = "n/a";
}else{
$cell = $this->input->post('CELLNO');
}
if($this->input->post('AGENCY_NO') = NULL){
$agency = "n/a";
}else{
$agency = $this->input->post('AGENCY_NO');
}
$input = array(
'ID_NUM' => $this->uri->segment(3),
'FNAME' => $this->input->post('FNAME' ),
'SURNAME' => $this->input->post('SURNAME' ),
'DO_BIRTH' => $this->input->post('DO_BIRTH' ),
'POBIRTH' => $this->input->post('POBIRTH' ),
'SEX' => $this->input->post('SEX' ),
'CIVILSTAT' => $this->input->post('CIVILSTAT' ),
'ID_NAT' => $this->input->post('ID_NAT' ),
'HEIGHT' => $this->input->post('HEIGHT' ),
'WEIGHT' => $this->input->post('WEIGHT' ),
'BLOOD_TYPE' => $this->input->post('BLOOD_TYPE' ),
'RES_ADD' => $this->input->post('RES_ADD' ),
'RES_ZIP' => $this->input->post('RES_ZIP' ),
'PERM_ADD' => $this->input->post('PERM_ADD' ),
'PERM_ZIP' => $this->input->post('PERM_ZIP' ),
'MNAME' => $mname,
'EXTENSION' => $ext,
'EMAIL' => $email,
'CELLNO' => $cell,
'AGENCY_NO' => $agency,
'DATE_CREATED' => date("Y-m-d")
);
$insert = $this->db->insert($this->table,$input);
return $insert;
}
but the problem is that i get this error Can't use method return value in write context says that its on line 108. which, the line 108 is the first if of my model. what is my error? and is there any codes which will be shorter?
You're only stating 1 = in your IF statements, for future note: It should be 2 ='s in a match.
I restructured this for you so your code is more readable and short.
// Checking if they're null and appending n/a if they're
$example = array('MNAME','EXTENSION','EMAIL', 'CELLNO', 'AGENCY_NO');
$new = array();
foreach ($example as $_ex)
{
$check = $this->input->post($_ex);
if ($check == null)? array_push($new, 'n/a') : array_push($new, $check);
}
Then replace with this (keeping in mind index's start at 0 in an array):
// Inside your DB insert query
'MNAME' => $new[0],
'EXTENSION' => $new[1],
'EMAIL' => $new[2],
'CELLNO' => $new[3],
'AGENCY_NO' => $new[4],
I hope this helped.
I want to insert into "invoicesout" not "invoice".
The problem is when I execute the line is added in the table invoice
I want to now where can i find the file who speak with mysql
InvoiceOutController.php
public function create()
{
$invoiceSettings = InvoiceSetting::find(1);
$data = array(
'clients' => Project::all(),
'products' => Product::where('status', 1)->get(),
'currencies' => Currency::all(),
'taxes' => Tax::orderBy('value', 'asc')->get(),
'invoiceCode' => isset($invoiceSettings->code)
$invoiceSettings->code : false,
'invoiceNumber' => isset($invoiceSettings->number) ?
$invoiceSettings->number + 1 : false
);
return View::make('user.invoiceout.create', $data);
}
public function store()
{
if ( Auth::user()->role_id != 1 )
{
return Redirect::to('dashboard')->with('error', trans('translate.permissions_denied'));
}
$rules = array(
'client_id' => 'required',
'number' => 'required',
'start_date' => 'required|date|date_format:"Y-m-d"',
'due_date' => 'required|date|date_format:"Y-m-d"',
'currency_id' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes())
{
$invoiceSettings = InvoiceSetting::first();
if (isset($invoiceSettings->number))
{
$invoiceNumber = $invoiceSettings->number + 1;
$invoiceSettings->number = $invoiceNumber;
$invoiceSettings->save();
}
$store = new Invoiceout;
$store->number = isset($invoiceSettings->number) ? $invoiceNumber : Input::get('number');
$store->status_id = 2;
$store->discount = Input::get('invoiceDiscount') ? Input::get('invoiceDiscount') : 0;
$store->type = Input::get('invoiceDiscountType') ? Input::get('invoiceDiscountType') : 0;
$store->amount = $store->calculateInvoice(Input::get('qty'), Input::get('price'), Input::get('taxes'), Input::get('discount'), Input::get('discountType'), Input::get('invoiceDiscount'), Input::get('invoiceDiscountType'));
$store->fill(Input::all());
$store->save();
$products = Input::get('products');
foreach ($products as $k => $v)
{
$product = new InvoiceProduct;
$product->invoice_id = $store->id;
$product->product_id = $v;
$product->quantity = Input::get('qty')[$k];
$product->price = Input::get('price')[$k];
$product->tax = Input::get('taxes')[$k];
$product->discount = Input::get('discount')[$k] ? Input::get('discount')[$k] : 0;
$product->discount_type = Input::get('discountType')[$k] ? Input::get('discountType')[$k] : 0;
$product->discount_value = $store->calculateProductPrice(1, Input::get('qty')[$k], Input::get('price')[$k], Input::get('taxes')[$k], Input::get('discount')[$k], Input::get('discountType')[$k]);
$product->amount = $store->calculateProductPrice(2, Input::get('qty')[$k], Input::get('price')[$k], Input::get('taxes')[$k], Input::get('discount')[$k], Input::get('discountType')[$k]);
$product->save();
App::make('ProductController')->manageQuantity($v, Input::get('qty')[$k], Input::get('price')[$k]);
}
$invoiceout = new Invoiceout;
$invoiceout->invoiceStatus();
}
else
{
$invoiceSettings = InvoiceSetting::find(1);
$data = array(
'clients' => Project::all(),
'products' => Product::where('status', 1)->get(),
'currencies' => Currency::all(),
'taxes' => Tax::all(),
'invoiceCode' => isset($invoiceSettings->code) ? $invoiceSettings->code : false,
'invoiceNumber' => isset($invoiceSettings-
>number) ? $invoiceSettings->number + 1 : false,
'errors' => $validator->errors(),
'inputs' => Input::all()
);
return View::make('user.invoiceout.create', $data);
}
return $this->loadDataTable();
}