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();
}
Related
I'm trying to get all item series from a deposit but the deposit id is on a related table. On this function i'll list all the series between two sequences requested
public function getSeries($params = [])
{
$data = collect($params);
$inicio = $data->only('serie_in');
$fim = $data->only('serie_fi');
$depOrigem = $data->only('id_origem');
$series = [];
for($i = $inicio; $i <= $fim; ++$i)
{
$item = Item::leftJoin('produtoItem', 'produtoItem.id', '=', 'item.id_produtoItem')->where('serie', $i)->where('produtoItem.id_deposito', $depOrigem)->first();
if(empty($item))
{
$status = 'I';
}
else
{
$status = $item->status;
}
$series[] = [
'serie' => $i,
'status' => $status
];
}
$result = [
'status' => true,
'data' => $series
];
return $result;
}
This is the error message, i'm thinking that must be as sintax error, but a dont realy know what? Can you help me?
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 2031 (SQL: select * from item left join produtoItem on produtoItem.id = item.id_produtoItem where serie = ? limit 1) in file /usr/share/nginx/html/controleestoque/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 671
I was calling the request on my controller without a validator, so i rewrite the getSeries method.
public function getSeries(Request $request){
$data = $request->only(['serie_in', 'serie_fi', 'id_origem']);
$result = $this->produto_service->getSeries($data);
return response()->json($result);
}
And my function work it !
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.
In am getting Undefined variable: score (View: C:\Users\Sarthak\blog\resources\views\submitquestion.blade.php) in blade view when executing :
Controller part
public function question(Request $request)
{
static $startscore = 0;
$getidvalue = Input::get('getid');
$getanswervalue = Input::get('getanswer');
$dbscore = DB::table('5question')->select('question_id', 'correct_answer', 'question_marks')->where('question_id', '=', $getidvalue)->get();
foreach($dbscore as $value) {
if ($getanswervalue == ($value->correct_answer)) {
$getscore = $startscore + $value->question_marks;
}
elseif ($getanswervalue == null) {
$emptyvalue = - 1;
$getscore = $startscore + $emptyvalue;
}
else {
$novalue = 0;
$getscore = $startscore + $novalue;
}
}
echo "$getscore";
Session::push('getscoresession', $getscore);
$getsession = ['qid' => $getidvalue, 'answer' => $getanswervalue];
Session::push('answer', $getsession);
// return response()->json(['qid'=>$getidvalue,'answer'=>$getanswervalue]);
$score = array_sum(Session::get("getscoresession"));
// return view('submitquestion',compact('score'));
return view('submitquestion', ['score' => $score]);
}
Blade part :
You have submitted quiz and your score is : {{ $score }}>
LOGOUT
try this one:
return view('submitquestion', compact('score'));
you can pass variable form controller to view using with and compact:
$request->session()->put('getscoresession', $getscore);
$getsession = ['qid' => $getidvalue, 'answer' => $getanswervalue];
$request->session()->put('answer', $getsession);
if ($request->session()->has('getscoresession')) {
$score = array_sum($request->session()->get("getscoresession"));
}else{
$score = 0;
}
using with :
$score= 10;
return view('submitquestion')->with('score',$score);
using compact :
return view('submitquestion',compact('score'));
Try it. If you get error from your controller send $score = 10;
return view('submitquestion')->with(['score' => $score]);
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.
I'm working with a couple of arrays, one of which has keys that are the productid, the value being an object that contains a doctrine entity of that product. Similarly, I have a plan with the index being the plan Id. For this for loop, I need to go through and individually set up invoices for each plan-product pair (the quantity will always be the same between them, except in cases where a user is purchasing a plan for an already owned device). Obviously this is somewhat complicated, so I'm not exactly sure how to phrase this question. An error occurs at the commented line, "Notice: Undefined Index"
for ($i = 0; $i < $totalInvoices; $i++) {
if ($i == $planQuantity[key($plans)]) {
next($plans);
}
if ($i == $productQuantity[key($products)]) {
next($products);
}
$data = array(
'planId' => key($plans),
//below here, I'm thinking at key($products) is where the error occurs
'productId' => key($products) != 0 ? key($products) : $plans[key($plans)]->getPricingTier()->getProductId(),
'userId' => $this->userId,
'paymentMethodId' => $paymentMethodId
);
if ($order['hasProduct'] || isset($order['activating'])) {
if (!isset($order['activating'])) {
$planModel->createDevicePlan($data);
$productAmount = $products[key($products)]->getAmount();
} else {
$data['deviceId'] = $order['activating']['inventoryId'];
$planModel->createDevicePlan($data, date('Y-m-d'));
$productAmount = 0;
}
} else {
$productAmount = 0;
}
if ($iteration % 5 == 0 && $order['hasShipping']) {
$invoiceShippingAmount = $billingModel->getShippingAmount($shippingOptionsId);
} else {
$invoiceShippingAmount = 0;
}
$salesData = array(
'paymentMethodsId' => $paymentMethodId,
'planAmount' => $plans[key($plans)]->getAmount(),
'planId' => key($plans),
'productAmount' => $productAmount,
'productId' => key($products),
'shippingAddressesId' => $shippingAddressId,
'shippingAmount' => $invoiceShippingAmount,
'shippingOptionsId' => $shippingOptionsId,
'transactionId' => $transactionId,
'userId' => $this->userId
);
$iteration++;
$billingModel->createInvoice($salesData);
}
Any help would be greatly appreciated.
Based on your comment reply, I think this will help
$plans_on_invoice = 0;
$products_on_invoice = 0;
for ($i = 0; $i < $totalInvoices; $i++) {
next($plans);
if ($plans_on_invoice == 0) {
$plans_on_invoice = $planQuantity[key($plans)];
}
plans_on_invoice--;
next($products);
if ($products_on_invoice == 0) {
$products_on_invoice = $productQuantity[key($products)];
}
products_on_invoice--;