repeating a php code without coding multiple times - php

This is my code:
if (preg_match('/^\/start (.*)/', $text, $match) or preg_match('/^\/get_(.*)/', $text, $match)) {
$id = $match[1];
if (isJoin($from_id)) {
$fileData = mysqli_query($db, "SELECT * FROM `file` WHERE `id` = '{$id}'");
$file = mysqli_fetch_assoc($fileData);
if (mysqli_num_rows($fileData)) {
if ($file['password']) {
sendMessage($from_id, "please send pass :", "markdown", $btn_back, $message_id);
mysqli_query($db, "UPDATE `user` SET `step` = 'password', `getFile` = '$id' WHERE `from_id` = '$from_id'");
} else {
$downloads = number_format($file['downloads']);
$downloads++;
$caption = urldecode($file['caption']);
Ilyad("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file['file_id'],
'caption' => "šŸ“„ count : <code>{$downloads}</code>\n{$caption}\n Thanks",
'parse_mode' => "html",
]);
Ilyad("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file['file_id2'],
'caption' => "šŸ“„ count : <code>{$downloads}</code>\n{$caption}\n Thanks",
'parse_mode' => "html",
]);
mysqli_query($db, "UPDATE `file` SET `downloads` = `downloads`+1 WHERE `id` = '$id'");
mysqli_query($db, "UPDATE `user` SET `step` = 'none', `downloads` = `downloads`+1 WHERE `from_id` = '$from_id'");
}
} else sendMessage($from_id, "hi welcome to bot", 'markdown', $btn_home, $message_id);
} else {
joinSend($from_id);
mysqli_query($db, "UPDATE `user` SET `getFile` = '$id' WHERE `from_id` = '$from_id'");
}
}
so what i want to do is repeat this code like 24 times but each time the number at the end of file_id changes like file_id1, file_id2, file_id3, ..., file_id24.
and the values for file_id1, ... and others are stored on my SQL database.
Now if you see there is two codes repeating and the only change is the number at the end of file_id so i want to make it 24 codes but instead of just repeating it I want to do it with one code.
and another thing I said 1 to 24 can i also do something so it reads the last number from a database value to like loop from 1 to x and x is the number i entered in database.
sorry i'm new to programming.

All you need to do is wrap that code in a for loop that increments 1..N. Then in the body of the loop, append / interpolate the loop increment variable where you need it.
for ($i = 1; $i <= 24; $i++) {
// ...
("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file["file_id$i"],
'caption' => "šŸ“„ Count : <code>{$downloads}</code>\n{$caption}\nšŸŸ” Thanks",
'parse_mode' => "html",
]);
}

Related

Problem in duplication after clicking submit button multiple times

My main problem is with that code in which when I click on submit buttons many times, it inserts duplication many times in the database in which I need to avoid that. Please help me to solve this problem. These are the two tables in which I am trying to insert. mat_ans_options_choose and mat_answer.
$val = $this->input->post(null, true);
$val['id'] = $this->input->post('id');
$val['sub_type'] = $this->input->post('sub_type');
$val['timeout'] = $this->input->post('timeout');
$val['level'] = $this->input->post('level');
$val['mat_category'] = $this->input->post('mat_category');
$option = $val['option'] = $this->input->post('option');
$type = $this->input->post('type');
$marks = [];
$uid = $this->session->userdata('id');
if (isset($val['id']) && isset($option)) {
$query = $this->db->query("SELECT * FROM mat_ans_options WHERE deleted=0 AND active=1 AND question=" . $val['id']);
$result = $query->result_array();
if ($query->num_rows() > 0) {
$count1 = 1;
foreach ($result as $res) {
if ($res['marks'] == 1) {
break;
} else {
$count1++;
}
}
}
// MAT answers options choose
$query1 = $this->db->query("SELECT * FROM mat_ans_options_choose WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id']);
$result1 = $query1->result_array();
if ($query1->num_rows() > 0) {} else {
$data1 = [
'uid' => $uid,
'q' => $val['id'],
'option_chose' => $option,
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_ans_options_choose', $data1);
}
if ($count1 == $option) {
$marks = 1;
} else {
$marks = 0;
}
// if($marks==1 || $marks==0)
// {
// MAT answers
$query2 = $this->db->query("SELECT * FROM mat_answers WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id'] . " AND type=" . $type . " AND sub_type=" . $val['sub_type'] . " AND level=" . $val['level']);
$result2 = $query2->result_array();
if ($query2->num_rows() > 0) {} else {
$data = [
'uid' => $uid,
'q' => $val['id'],
'type' => $type,
'level' => $val['level'],
'sub_type' => $val['sub_type'],
'mat_category' => $val['mat_category'],
'marks' => $marks,
'timeoutstatus' => $val['timeout'],
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_answers', $data);
}
// }
return 1;
} else {
return 0;
}
Use JS in which you disable the button after first click - it will work no matter if you are using AJAX or not.
You can use JS/jQuery to limit the number of requests made on the client side. For example by disabling the button on submit:
$("#my-button").prop("disabled", true);
But if the data is sensitive for duplicates (orders, user registration etc) you should make the request limit server side with PHP. You can achieve this by adding a unique index to the tables, either on user id or on a unique token that is submitted with the html form.
Create UNIQUE index in database for uid and q. The database will not insert same question's id from same user's id mulitple times.

Unique code generation using Last Insert Id in Code Igniter?

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

Auto increment Invoice ID in Code-igniter

i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.

Speeding up a very slow PHP script generating a large JSON array

I currently have a web-app running on AppEngine that uses PHP to initially generate a giant JSON array, which Javascript then uses to populate elements of my web-app.
The following code works perfectly and does everything I want, however takes about 10 seconds to execute. Might not sound like a lot, but it certainly feels out of place. I'm wondering what I should be doing differently to speed up the creation of the initial array.
I've so far thought about attacking this a few ways;
I could load less data initially, reducing load times as there is
literally less to load. This would effect the general performance
though, as right now once the data is loaded, each "section" is
instant to be populated and super fast.
I could cache some data using App Engine's
built in Memcache. This is a neat idea however the data generated
changes often. Often enough that a cache just wont do it.
Use Web
Sockets instead. I want to eventually do this, and it's on the to-do
list, however this would mean rewriting a lot of code, so I'm not too
fond of this right now.
I'm sure there are some "bad practise" bits and pieces within my code as well, feel free to point them out and scold me for it... Here's the same code below as a Gist if you prefer it that way.
<?php
use google\appengine\api\cloud_storage\CloudStorageTools;
# ===================================== #
# ==== Generate App Settings Array ==== #
# ===================================== #
//Existing Class (not shown) already generated $app for us...
$app_settings_array = array('app_version' => $app->app_version, 'app_server' => $_SERVER['SERVER_SOFTWARE'], 'app_id' => $app->app_id, 'app_name' => $app->app_name, 'app_logo_dark' => $app->app_logo_dark, 'app_logo_light' => $app->app_logo_light, 'app_motd' => $app->app_motd, 'app_domain' => $app->app_domain);
# ===================================== #
# ==== Generate User Details Array ==== #
# ===================================== #
$currentuser = $_SESSION['user_id']; //Get current user id from session
$user_info = $db->prepare("SELECT * FROM hr_personal WHERE employee_id = :user_id LIMIT 1");
$user_info->bindParam(':user_id', $currentuser);
$user_info->execute();
$user = $user_info->fetch(PDO::FETCH_OBJ);
$email_hash = hash_hmac('sha256', $user->employee_id, '_redactedkey');
$log_info = $db->prepare("SELECT log_time FROM app_log WHERE log_user = :user_id ORDER BY log_time ASC LIMIT 1"); //Get
$log_info->bindParam(':user_id', $currentuser);
$log_info->execute();
$first_seen = $log_info->fetch(PDO::FETCH_OBJ);
$user_details_array = array('id' => $user->employee_id, 'id_hash' => $email_hash, 'first_seen' => $first_seen->log_time, 'title' => $user->employee_title, 'name' => $user->employee_knownas, 'avatar' => $user->employee_avatar, 'mobile' => $user->employee_mobile, 'email' => $user->employee_email);
# ============================= #
# ==== Generate Chat Array ==== #
# ============================= #
$currentuser = $_SESSION['user_id'];
$currentapp = $app->app_id;
$chat_array = array();
foreach (range('A', 'Z') as $char) {
$individuals = array();
$countrow = $db->prepare("SELECT * FROM hr_personal where employee_knownas LIKE '$char%' AND employee_id IN (SELECT notification_submitter FROM notification_sent WHERE notification_id IN (SELECT notification_id FROM notification_wait WHERE user_id = '$currentuser' AND method = 'online' ORDER BY notification_id DESC))");
$countrow->execute();
if ($countrow->rowCount() > 0) {
$mesage_query = "SELECT * FROM hr_personal where employee_knownas LIKE '$char%' AND employee_id IN (SELECT notification_submitter FROM notification_sent WHERE notification_id IN (SELECT notification_id FROM notification_wait WHERE user_id = '$currentuser' AND method = 'online' ORDER BY notification_id DESC))";
$message_query_run = $db->query($mesage_query);
while($row = $message_query_run->fetch(PDO::FETCH_ASSOC)) {
if(!empty($row['employee_avatar'])){
$options = ['size' => 200, 'crop' => true];
$image_file = "gs://rouic-cdn/internal/".$row['employee_avatar'];
$image_url = CloudStorageTools::getImageServingUrl($image_file, $options);
$image_url = preg_replace("/^http:/i", "https:", $image_url);
} else {
$image_url = "";
}
$whileUser = $row['employee_id'];
$message_chain = array();
$chain_query = "SELECT * FROM notification_wait WHERE method = 'online' AND user_id = '$currentuser' AND notification_id IN (SELECT notification_id FROM notification_sent WHERE notification_submitter = '$whileUser')";
$chain_query_run = $db->query($chain_query);
while($chainRow = $chain_query_run->fetch(PDO::FETCH_ASSOC)) {
array_push($message_chain, array('id' => $chainRow['notification_id'], 'reply_id' => $chainRow['reply_id'], 'content' => $chainRow['message'], 'time' => $chainRow['time'], 'state' => $chainRow['state']));
}
array_push($individuals, array('id' => $row['employee_id'], 'group' => $char, 'name' => $row['employee_knownas'], 'avatar' => $image_url, 'message_chain' => $message_chain));
}
array_push($chat_array, array('group' => $char, 'data' => $individuals));
}
}
# ========================================== #
# ==== Generate Admin Groups (if admin) ==== #
# ========================================== #
$admin_array = array();
if($auth->checkPage('admin', $_SESSION['user_id']) == false){ //Existing CheckPage class returns true if user is allowed on page
array_push($admin_array, array('access' => 'denied'));
} else {
//Generate All Clients
$client_array = array();
$client_query = "SELECT * FROM clients WHERE client_app = '$currentapp'";
$client_query_run = $db->query($client_query);
while($row = $client_query_run->fetch(PDO::FETCH_ASSOC)) {
if(!empty($row['client_avatar'])){
$options = ['size' => 200, 'crop' => true];
$image_file = "gs://rouic-cdn/internal/".$row['client_avatar'];
$image_url = CloudStorageTools::getImageServingUrl($image_file, $options);
$image_url = '<span class="thumbnail-wrapper d48 circular inline m-t-5">
<img id="dynamicavy" src="'.preg_replace("/^http:/i", "https:", $image_url).'" width="48" height="48">
</span>';
} else {
$image_url = "";
}
$short_desc = strlen($row['client_desc']) > 30 ? substr($row['client_desc'],0,30)."..." : $row['client_desc'];
$desc = '<span class="expandable" full-length="'.$row['client_desc'].'">'.$short_desc.'</span>';
$actions = '<button class="btn btn-xs btn-primary">Edit Details</button>';
array_push($client_array, array($row['client_id'], $image_url, "<b>".ucwords($row['client_name'])."</b>", $row['client_dob'], $row['client_phone'], $row['client_address'], $desc, $actions));
}
//Generate All Departments
$department_array = array();
$department_query = "SELECT * FROM departments WHERE dep_app = '$currentapp'";
$department_query_run = $db->query($department_query);
while($row = $department_query_run->fetch(PDO::FETCH_ASSOC)) {
if(!empty($row['dep_avatar'])){
$options = ['size' => 200, 'crop' => true];
$image_file = "gs://rouic-cdn/internal/".$row['dep_avatar'];
$image_url = CloudStorageTools::getImageServingUrl($image_file, $options);
$image_url = '<span class="thumbnail-wrapper d48 circular inline m-t-5">
<img id="dynamicavy" src="'.preg_replace("/^http:/i", "https:", $image_url).'" width="48" height="48">
</span>';
} else {
$image_url = "";
}
$short_desc = strlen($row['dep_description']) > 30 ? substr($row['dep_description'],0,30)."..." : $row['dep_description'];
$desc = '<span class="expandable" full-length="'.$row['dep_description'].'">'.$short_desc.'</span>';
$actions = '<button class="btn btn-xs btn-primary">Edit Details</button>';
array_push($department_array, array($row['dep_id'], $image_url, "<b>".ucwords($row['dep_name'])."</b>", $desc, $actions));
}
array_push($admin_array, array('access' => 'granted', 'allDepartments' => $department_array, 'allClients' => $client_array));
}
... About 4 More sections redacted ...
# ===================== #
# ==== Final Array ==== #
# ===================== #
$init_array_compare = array('chat' => $chat_array, 'admin' => $admin_array, 'app_details' => $app_settings_array, 'user_details' => $user_details_array, 'user_permissions' => $user_permissions_array);
$hash = md5(json_encode($init_array_compare)); //I'm basically creating a hash of the results here so I can see if anything has changed if generated again
$init_array = array('hash' => $hash, 'chat' => $chat_array, 'admin' => $admin_array, 'app_details' => $app_settings_array, 'user_details' => $user_details_array, 'user_permissions' => $user_permissions_array);
echo json_encode($init_array);
MonkeyZeus was completely correct, it turned out to be CloudStorageTools::getImageServingUrl() causing the hanging. After writing a script to cache the URL's it generated the script now runs in under a second.

Create uniqueID based on id mysql laravel 5

I want to create uniqueID for column transid like autoincrement. but I already have a column id (autoincrement).
column transid should be 01000001 and autoincrement, or follow column id number.
here is my code
public function insertFund($request,$lender, $ftype, $sign)
{
$fmamt = str_replace(".","",$request->fmamt );
$fdesc = $request->fdesc;
$fdate = $request->fdate;
$trnsfer = $request->file('upload_trnsfer');
$transid = "01".str_pad($fund->id, 5, '0', STR_PAD_LEFT);
if($fdesc == null)
{
$fdesc = '';
}
$fund = $this->fund->create([
'lender_id' => $lender->id,
'transid' => $transid,
'fmamt' => $fmamt,
'refdc' => '',
'ftype' => $ftype,
'sign' => $sign,
'fdesc' => $fdesc,
'fdate' => $fdate,
'fstat' => 'pending'
]);
return $fund;
}
I think, the core issue is here.
$transid = "01".str_pad($fund->id, 5, '0', STR_PAD_LEFT);
How should I write code in for this?
Thanks in Advance.
Try this, Hope this help you
$temp_str = '00000000';
Last inserted id
$obj_fund = Fund::get()->last();
$last_inserted_id = $obj_fund->id;
$temp_index = $last_inserted_id + 1;
$id_length = strlen($temp_index);
$temp_id = substr_replace($temp_str, $last_inserted_id, -$id_length);
Your get 00000012

Categories