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?
Related
I have a google task which gets all companies from my firebase database. I then go through each of those companies in a loop and call additional task for updating each specific company. My problem is that my companies count is increasing and when doing foreach like this i can get into memory limit issues. Here is the actual code for calling the tasks and subtasks:
$router->get('companies', function () use ($router) {
$slackDataHelpersService = new \App\Services\SlackDataHelpersService();
$companiesDocuments = $slackDataHelpersService->getCompanies();
foreach ($companiesDocuments->documents() as $document) {
$cid = $document->id();
createTask('companies', 'updateCompany', "{$cid}");
}
return res(200, 'Task done');
});
How can i separate my initial companies documents into chunks and call a task for each of those chunks? For example, a task that will go through every 100 documents instead of the whole list?
Here is what i tried without success(i used members in this case):
$router->get('test2', function () use ($router) {
$db = app('firebase.firestore')->database();
$membersRef = $db->collection('companies')->document('slack-T01L7H2NDPB')->collection('members');
$query = $membersRef->orderBy('created', 'desc')->limit(10);
$perPage = 10;
$batchCount = 10;
$lastCreated = null;
while ($batchCount == $perPage) {
$loopQuery = clone $query;
if ($lastCreated != null) {
$loopQuery->startAfter($lastCreated);
}
$docs = $loopQuery->documents();
$docsRows = $docs->rows();
$batchCount = count($docsRows);
if ($batchCount > 1) {
$lastCreated = $docsRows[$batchCount - 1];
}
echo $lastCreated['created'];
//createTasksByDocs($docs);
}
//return res(200, 'Task done');
});
I ended up making a function which uses a while loop and loops until it reaches the limit:
function paginateCollections($ref, $limit, $functionName)
{
$query = $ref->orderBy('created', 'desc')->limit($limit);
$perPage = $limit;
$batchCount = $limit;
$lastCreated = null;
while ($batchCount == $perPage) {
$loopQuery = clone $query;
if ($lastCreated != null) {
$loopQuery = $loopQuery->startAfter([$lastCreated]);
}
$docs = $loopQuery->documents();
$docsRows = $docs->rows();
$batchCount = count($docsRows);
if ($batchCount > 1) {
$lastCreated = $docsRows[$batchCount - 1]['created'];
}
if (function_exists($functionName)) {
$functionName($docs);
}
}
}
I am working with rest api using codeigniter,I want to fetch records + total records + per page records,but not worked for me
Here is my function in controller
<?php
public function search_shop()
{
$users['rec'] = $this->Model_users->find_shop($_POST);
if($users['rec']!="")
{
$responseJSON = array("Status" => true,"Result" => $users['rec']);
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
else
{
$responseJSON = array("Status" => false,"Message" => "There is no matching record");
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
}
And here is my "find_shop" function in model,How can i fetch all records with total number of records and per page records ?
public function find_shop()
{
$add_data['page_number'] = ($this->input->post('page_number') && !empty($this->input->post('page_number'))) ? $this->input->post('page_number') : NULL;
$add_data['search'] = ($this->input->post('search') && !empty($this->input->post('search'))) ? $this->input->post('search') : NULL;
$records="10";
$mins="10";
if($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
{
$starting_row="0";
$last_row="10";
}
else
{
$last_row="9";
$cd="1";
$lim="10";
$starting_row=$add_data['page_number']*$lim-$last_row-$cd;
$last_row=$add_data['page_number']*$records-$cd;
}
$this->db->select('*');
$this->db->from('shop s');
$this->db->like('shop_name',$add_data['search']);
$this->db->or_like('city',$add_data['search']);
$this->db->limit($last_row,$starting_row);
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$row = $query->result_array();
return $row;
return $query->num_rows;
}
else
{
return false;
}
}
?>
Try This, Hope it helps
in the Controller please test this after model related changes
$users = array();
$users = $this->Model_users->find_shop($_POST);
echo'<pre>';print_r($users);die;
in the Model, There is a mistake in the return, You cannot do two return at the same time
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$data = array();
$data['row'] = $query->result_array();
$data['total_records'] = $this->db->count_all_results('shop');
$data['per_page_records'] = $query->num_rows();
return $data;
}else{
return array('row'=>array(),'total_records'=>'0','per_page_records'=>'0');
}
Change your if condition like this:
$records="10"; // This is records per page showing
if ($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
{
$starting_row="0";
} else {
$starting_row = ($add_data['page_number'] - 1) * $records;
}
You need to set limit and offset of query. For example: limit 0, 10: this will show first 10 records. Here 0 is starting point and 10 is the length of records which you want to show. 10 will always be same as you are showing 10 records. Limit 10, 10: it will show records from 10 to 19. hope it clears your doubt.
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 currently running a wordpress backend and want to display some tweets based on hastags on my website. For the general API request and database storage, I use this function:
private function parseRequest($json) {
$tmp = $json;
$result = array();
if (isset($json['statuses'])) {
$tmp = $json['statuses'];
}
if (isset($tmp) && is_array($tmp)){
foreach ($tmp as $t) {
$this->image = null;
$this->media = null;
$tc = new \stdClass();
$tc->feed_id = $this->id();
$tc->id = $t['id_str'];
$tc->type = $this->getType();
$tc->nickname = '#'.$t['user']['screen_name'];
$tc->screenname = (string)$t['user']['name'];
$tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
$tc->system_timestamp = strtotime($t['created_at']);
$tc->text = $this->getText($t);
$tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
$tc->permalink = $tc->userlink . '/status/' . $tc->id;
$tc->media = $this->getMedia($t);
#$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
}
}
return $result;
}
Now I am looking for a function that counts all the variable in the "additional array together e.g. shares + likes + comments and sorts all posts based on the resulting number.
I am using the standard wordpress sql database. I cannot find a solution or I am just blind.
Thanks in regards
You could use a simple usort function:
usort($tc, function($a, $b) {
$a_sum = array_sum($a->additional);
$b_sum = array_sum($b->additional);
if ($a_sum == $b_sum) {
return 0;
}
return ($a_sum < $b_sum) ? -1 : 1;
});
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.