Laravel : Undefined variable in blade? - php

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

Related

Set the value of a variable based on the value of another variable php

New to programming and looking for help please,
i need to the set the value of $b_num based on the value of $egg_type i have tried using an if statement but not having any luck
`
$egg_type = $row["egg_type"] ;
if ($egg_type == 'M/S Select Farm')
{
$b_num = '1';
}
if ($egg_type = 'Free Range')
{
$b_num = '1';
}
if ($egg_type = 'Barn')
{
$b_num = '2';
}
if ($egg_type =='Intensive')
{
$b_num = '3';
}
if ($egg_type == 'Organic')
{
$b_num = '0';
}
if ($egg_type == 'Brioche')
{
$b_num = '3';
}
`
Tried the if statement but the value didnt change,
First you've to check if your $egg_type variable is being set in order not to make errors later
Second you can do it like this
if(isset($egg_type)) {
if(in_array($egg_type, ['M/S Select Farm', 'Free Range'])) {
$b_num = 1;
} elseif(in_array($egg_type, ['Intensive', 'Brioche'])) {
$b_num = 3;
} elseif($egg_type === 'Organic') {
$b_num = 0;
} elseif($egg_type === 'Barn') {
$b_num = 2;
}
}
Maybe $egg_type is null value. Therefore,you can improve your code (PHP 8.0 version) and set default value for b_num like this:
$egg_type = $row["egg_type"] ;
$b_num = match($egg_type) {
'M/S Select Farm' => 1,
'Free Range' => 1,
'Barn' => 1,
'Intensive' => 1,
'Organic' => 1,
'Brioche' => 1,
default => 'nothing any value for b_num'
};
echo $b_num;

How to check for a value on a different table?

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

Simple pagination in laravel?

I am working with simple pagination in laravel. I am fetching 20 records from the database in a foreach loop and making a quiz. I want to skip some question in between quiz by applying if condition in controller part...like I want to skip question number 10 and 11. How to proceed in simple pagination?
Controller part :
public function choosequestion(Request $request){
if(Session::get('storepercentage') < 60){
$getquestion = DB::table('5question')->select('question_id','question','choice1','choice2','choice3','choice4','question_level')
->where('question_level','=','easy')
->simplepaginate(1);
}
if(Session::get('storepercentage') > 60){
$getquestion = DB::table('5question')->select('question_id','question','choice1','choice2','choice3','choice4','question_level')
->where('question_level','=','medium')
->simplepaginate(1);
}
if($request->ajax()){
return view('ajax',['getquestions'=>$getquestion])->render();
}
return view('question5',['getquestions'=>$getquestion]);
}
Controller input part to calaculate % :
public function questionquiz5(Request $request){
static $startscore=0;
static $getscore;
static $level;
$getidvalue = Input::get('getid');
$getanswervalue = Input::get('getanswer');
$dbscore = \DB::table('5question')->select('question_id','correct_answer','question_marks','question_level')
->where('question_id','=',$getidvalue)
->get();
foreach ($dbscore as $easy) {//////easy questions start
if ( $getanswervalue==($easy->correct_answer) ){
$level = $easy->question_level;
$getscore = $startscore + $easy->question_marks;
}elseif($getanswervalue == null){
$getscore = 0;
$level = $easy->question_level;
}else{
$getscore = 0;
$level = $easy->question_level;
}
}
Session::push('getscoresession',$getscore);
$score = array_sum(Session::get("getscoresession"));
$epercentage = ($score / 8 ) * 100;
if($epercentage > 60){
Session::put('storepercentage', $epercentage);
echo "true";
echo $epercentage;
}else{
echo "false";
}
Session::push('level',$level);
$getsession = [ 'qid' => $getidvalue, 'answer' => $getanswervalue];
Session::push('answer', $getsession);
}
My issue is that I am getting a blank view for the second condition in simple pagination can we skip question like this?

how to implode and insert values into db in codeigniter?

How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:
id userid q_id answer_id time_taken
1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7
in my controller:
public function insert_result()
{
$this->load->model('quiz_models');
$user_id=$this->input->post('user_id');
$qq_id=$this->input->post('questionid');
$answer_id=$this->input->post('AnswerID');
$time_taken=$this->input->post('timetaken');
$question_no=$this->input->post('question_no');
$bd = "$question_no";
switch ($bd) {
case"1":
$data=array('user_id'=>$user_id,
'q_id'=>$qq_id,
'answer_id'=>$answer_id,
'time_taken'=>$time_taken);
$this->quiz_models->insert_result($data);
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
echo "something is wrong";
}
}
public function quiz_test()
{
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
'answer_id'=>$comma1,
'time_taken'=>$comma2);
$this->quiz_model->update_result($data);
}
}
}
and Model:
function insert_result($data)
{
$this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
}
function quiz_test()
{
$ses_id = $this->session->userdata('lastids');
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
$query = $this->dbb->query($sql);
$result = $query->result();
return $result;
}
function update_result($data){
$ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}
when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure
Normalize your Data
You should prevent to store your information in the table like that.
It should be possible to normalize your data properly. If you dont know
how to do that the following link could be interesting:
Normalization in MYSQL
However a possible solution would be to structure your data:
In order to do that - create a save Method in your Model to split between update and insert - this model could look like
class Quiz_Models
{
private $arrPostData;
public function save($arrPostData = false)
{
$this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData;
$id = $this->session->userdata("lastids");
if ($id)
{
$query = $this->db
->select("*")
->from("results")
->where("id",$id)
->get();
if ($query->num_rows() == 1)
{
$this->update($query->row(0));
}
else return false;
}
else
{
$this->insert();
}
if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
}
private function update($objData)
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $objData->userid;
$objCollection->id = $objData->id;
$arrData = explode($objData->q_id);
foreach($arrData AS $key => $quizId)
{
$objQuiz = new stdClass();
$objQuiz->q_id = $quizId;
$objQuiz->answer_id = explode($objData->answer_id)[$key];
$objQuiz->time_taken = explode($objData->answer_id)[$key];
$objCollection->append($objQuiz);
}
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db
->where("id",$objCollection->id)
->update("results",$objCollection->getDbData());
}
private function insert()
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $this->arrPostData['user_id'];
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db->insert("results",$objCollection->getDbData());
$this->session->set_userdata("lastids", $this->db->insert_id());
}
}
as an addition you need a Collection Object (put this below your model)
class Quiz_Collection extends Array_Object
{
public $userId = 0;
public $id = 0;
public function addQuizFromPost($objQuiz)
{
if (intval($objQuiz->q_id) > 0)
{
foreach($this AS $key => $obj)
{
if ($obj->q_id == $objQuiz->q_id)
{
$this->offsetSet($key, $objQuiz);
return true;
}
}
$this->append($objQuiz);
return true;
}
return false;
}
public function sortQuizData($objA, $objB)
{
if ($objA->q_id == $objB->q_id) return 0;
return ($objA->q_id < $objB->q_id) ? -1 : 1;
}
public function getDbData()
{
$this->uasort(array($this,"sortQuizData"));
$arrData = $this->getArrayCopy();
$arrDbData = [
"userid" => $this->userId,
"q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
"answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
"time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
];
return $arrDbData;
}
}
pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.

PHP: how to return the right stuff

In my function I have more variables:
$disallowGallery = 1;
$disallowFriend = 1;
$disallowWall = 1;
$disallowPM = 1;
$disallowStatusComment = 1;
Now, i have a $check parameter. If it contains 'Gallery' the function should return the $disallowGallery variable. If it contains 'Friend' it should return the $disallowFriend variable.
I can do this myself with alot of if else statement / or an switch. But does there exist a more effective/simpler way?
The cleanest way to store this in my eyes would be an array:
$disallow = array(
"Gallery" => 1,
"Friend" => 1,
"Wall" => 1,
"PM" => 1,
"Comment" => 1
);
Inside a check function, you would do a check like so:
function check("Comment")
....
if (array_key_exists($area, $disallow))
return $disallow[$area];
else
return 0;
You can use variable variables:
function isDisallowed($type) {
$disallowGallery = 1;
$disallowFriend = 1;
$disallowWall = 1;
$disallowPM = 1;
$disallowStatusComment = 1;
$type = "disallowed$type";
return isset($$type) ? $$type : 1;
}
But I'd be more tempted to store your configuration in an associative array:
function isDisallowed($type) {
$disallowed = array (
'Gallery' => 1,
'Friend' => 1,
// ...
'StatusComment' => 1,
);
return array_key_exists($type, $disallowed) ? $disallowed[$type] : 1;
}
return ${'disallow' . $check};

Categories