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
Related
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",
]);
}
I have 2 tables one called Exams and the other Exam Results. In the exam I enter the passing_score and in the Exam Results I save the answer of the exam. I'm trying to look up the passing_score and if the passing score is greater then the result then the person passed.
Here is the entire function of this code
public function exam($course_id, Request $request)
{
$course = Course::where('id', $course_id)->firstOrFail();
$answers = [];
$exam_score = 0;
foreach ($request->get('question') as $question_id => $answer_id) {
$question = ExamQuestion::find($question_id);
$correct_answer = ExamOption::where('exam_question_id', $question_id)
->where('id', $answer_id)
->where('is_correct', 1)->count() > 0;
$answers[] = [
'exam_question_id' => $question_id,
'exam_option_id' => $answer_id,
'corect' => $correct_answer
];
if ($correct_answer) {
$exam_score += $question->score;
}
}
$exam_result = ExamResult::create([
'exam_id' => $course->exam->id,
'employee_id' => \Auth::id(),
'result' => $exam_score,
]);
$exam_result->answers()->createMany($answers);
$exam_id = ExamResult::all();
$final_results = Exam::where('id', $exam_id)->get(['passing_grade']);
$val = $final_results->passing_grade;
if($exam_result->result >= $val) {
$exam_result->is_complete = 1;
$exam_result->save();
}
return redirect()->route('learn.show', [$course, $request])->with('message', 'Test score: ' . $exam_score);
}
Here is the logic I've tried and I get stuck.
$exam_id = ExamResult::all();
$final_results = Exam::where('id', $exam_id)->get('passing_grade');
$val = $final_results->passing_grade;
if($exam_result->result >= $val) {
$exam_result->is_complete = 1;
$exam_result->save();
}
Here is the error I'm getting
Argument 1 passed to Illuminate\Database\Grammar::columnize() must be
of the type array, string given, called in
/Applications/MAMP/htdocs/QuickHS/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php
on line 137
Here is the database structure for the 2 tables
This is the exam table
This is the exam results table
Here is the correction. Please try this.
$final_results = Exam::where('id', $exam_id)->first();
$val = $final_results->passing_grade;
I've resolved it and here is how I did it
$final_results= Exam::first();
$x = $final_results->passing_grade;
if($exam_result->result >= $x)
{
$exam_result->is_complete = 1;
$exam_result->save();
}
I tried to find solutions
but i always get this error
You must specify an index to match on for batch updates.
public function editcompanionship()
{
$companionship_id = $this->input->post('companionship_id[]');
$missionary_one_id = $this->input->post('missionary_one_id[]');
$missionary_two_id = $this->input->post('missionary_two_id[]');
$missionary_three_id = $this->input->post('missionary_three_id[]');
$value_batch_update = array();
for($i=0; $i<count($companionship_id); $i++):
$value_batch_update[$i] = array(
'missionary_one_id' => $missionary_one_id[$i],
'missionary_two_id' => $missionary_two_id[$i],
'missionary_three_id' => $missionary_three_id[$i],
'modified' => date('Y-m-d H:i:s', time()),
);
endfor;
$this->db->where('companionship_id',$companionship_id[$i]);
$this->db->update_batch('pcdom_companionship',$value_batch_update);
$this->session->set_flashdata("success",alert("alert-success","Updated Successfully!"));
redirect(base_url('mrec/companionship'));
exit();
}
Can Any body knows?
The 3rd param of method update_batch() is required.
public function update_batch($table, $set = NULL, $index = NULL, $batch_size = 100)
{
....
if ($index === NULL)
{
return ($this->db_debug) ? $this->display_error('db_must_use_index') : FALSE;
}
...
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
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.