condition not satisfied still the php is running - php

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.

Related

How to save a database entry only twice per month on each id in CodeIgniter?

I'm developing a program using CodeIgniter. I want save a entry in database only twice every month on each id.
function save_task() {
$project_id = $this->input->post('project_id');
$id = $this->input->post('id');
$this->init_project_permission_checker($project_id);
if ($id) {
if (!$this->can_edit_tasks()) {
redirect("forbidden");
}
} else {
if (!$this->can_create_tasks()) {
redirect("forbidden");
}
}
$route_length = $this->input->post('route_length');
$fuel_milage = $this->input->post('fuel_milage');
$daily_consumption = $route_length / $fuel_milage;
$monthly_allowance = $daily_consumption * 26;
$title = $monthly_allowance / 2;
$data = array(
"route_length" => $this->input->post('route_length'),
"fuel_milage" => $this->input->post('fuel_milage'),
"daily_consumption" => $route_length / $fuel_milage,
"monthly_allowance" => $daily_consumption * 26,
"title" => $monthly_allowance / 2,
"description" => $this->input->post('description'),
"project_id" => $project_id,
"status" => $this->input->post('status'),
);
$reissue_date = time() + (13*24*60*60);
$data['deadline'] = date('Y-m-d',$reissue_date);
$data['start_date'] = get_current_utc_time();
//clint can't save the assign to and collaborators
$save_id = $this->Tasks_model->save($data, $id);
if ($save_id) {
if ($id) {
//updated
log_notification("project_task_updated", array("project_id" => $project_id, "task_id" => $save_id, "activity_log_id" => get_array_value($data, "activity_log_id")));
} else {
//created
log_notification("project_task_created", array("project_id" => $project_id, "task_id" => $save_id));
}
echo json_encode(array("success" => true, "data" => $this->_task_row_data($save_id), 'id' => $save_id, 'message' => lang('record_saved')));
} else {
echo json_encode(array("success" => false, 'message' => lang('error_occurred')));
}
}
How can I do that ? With each data id I can save only 2 post within 30 days, if I try to insert more than twice it deny to save.

How can I implement insert_batch active record in codeigniter in inserting multiple values?

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);

Compile Error Can't use method return value in write context in code igniter

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.

sms credit deduction concurrency issue

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;
}

How to compare array a with b and create new arrays c (items in a and b), d (items in a, not in b), and e (items in b, not in a)?

Consider the following arrays. They represent the top-5 performing employees for yesterday and today:
$yesterday = array(
6 => array('name' => 'Tod', 'score' => 9.5),
12 => array('name' => 'Jim', 'score' => 7.3),
18 => array('name' => 'Bob', 'score' => 8.4),
7 => array('name' => 'Jan', 'score' => 6.2),
20 => array('name' => 'Sam', 'score' => 6.0),
);
$today = array(
6 => array('name' => 'Tod', 'score' => 9.1),
9 => array('name' => 'Jef', 'score' => 9.3),
35 => array('name' => 'Axl', 'score' => 7.6),
7 => array('name' => 'Jan', 'score' => 6.5),
41 => array('name' => 'Ted', 'score' => 8.0),
);
I need 3 new arrays compiled from the above: $stay holding employees who were in the top-5 yesterday, and still are today, $gone, holding employees who were in the top-5 yesterday, but are not anymore, and $new, holding newcomers to $todays top-5 list:
// notice that the scores in $stay come from $today, not $yesterday
// also notice that index keys are maintained
$stay = array(
6 => array('name' => 'Tod', 'score' => 9.1),
7 => array('name' => 'Jan', 'score' => 6.5)
);
$gone = array(
12 => array('name' => 'Jim', 'score' => 7.3),
18 => array('name' => 'Bob', 'score' => 8.4),
20 => array('name' => 'Sam', 'score' => 6.0)
);
$new = array(
9 => array('name' => 'Jef', 'score' => 9.3),
35 => array('name' => 'Axl', 'score' => 7.6),
41 => array('name' => 'Ted', 'score' => 8.0)
);
I have no clue on how to build the logic here. I started with a loop, but didn't get far. I believe it should be something like this. Could you help me get this right?
for ($i = 0; $i < count($yesterday); $i++) {
// I'm comparing key numbers, but not key values
// how do I compare key values?
if (in_array($yesterday[$i], $today) {
// add to $stay array
}
else {
// add to $gone array
}
}
for ($i = 0; $i < count($today); $i++) {
if (!in_array($today[$i], $yesterday) {
// add to $new array
}
}
P.S. I don't know if this is helpfull, but $yesterday and $today are always of equal length (in this case, 5 items, but other scenarios are possible in which both arrays hold 7 or 10 items for instance). The combined items of $stay and $new logically are always equal to the number of items in either $yesterday or $today :-)
https://www.php.net/manual/function.array-intersect.php
https://www.php.net/manual/function.array-diff.php
$c = array_intersect($a, $b);
$d = array_diff($a, $b);
$e = array_diff($b, $a);
This can be accomplished using just a few of PHP's many powerful array functions:
$stay = array_intersect_assoc($yesterday, $today);
$gone = array_diff_assoc($yesterday, $today);
$new = array_diff_assoc($today, $yesterday);
I think this should work but isnt the fastest method to do this i think.
$stay = array();
$gone = array();
$new = array();
$found = false;
foreach($yesterday as $yKey)
{
$found = false;
foreach($today as $tKey)
{
if($tKey['name'] == $yKey['name'])
{
$found = true;
$stay[]['name'] = $tKey['name'];
break;
}
else
{
$found = false;
}
}
if($found == false)
{
$gone[]['name'] = $yKey['name'];
}
}
foreach($today as $tKey)
{
$found = false;
foreach($yesterday as $yKey){
if($yKey['name'] == $tKey['name'])
{
$found = true;
break;
}
else{
$found = false;
}
}
if($found == false)
{
$gone[]['name'] = $tKey['name'];
}
}

Categories