Welcome Guest, Not a member yet? Register   Sign In
Display Loading Image While Page Loads
#5

(This post was last modified: 09-18-2018, 01:36 AM by Pertti.)

This is what is generally called N+1 problem, where you create 1 query for every N items you need. This is usually bad approach, as each DB query, no matter how small, adds couple of milliseconds for checking the DB connection, sending query, waiting DB server response, etc.

You should be able to convert this into single query fairly quickly tho.

PHP Code:
$marks = [];
$q $this->db
    
->select('studentID, subjectID, mark')
    ->
where('classesID'$classID)
    ->
get('mark');
if (
$q->num_rows()) {
    foreach (
$q->result() as $row) {
        if (!isset(
$marks[$row->studentID])) {
            
$marks[$row->studentID] = [];
        }
       
        
$marks[$row->studentID][$row->subjectID] = $row->mark;
    }
}

foreach(
$students as $student) {
    
$studentID $student->student;
    foreach(
$subjects as $subject) {
        
$subjectID=$subject->subjectID;
        
$mark = isset($marks[$studentID][$subjectID]) ? $marks[$studentID][$subjectID] : false;
    }


So, basically, you get all the marks for one class in single query, then create reference array in PHP using array indexes as meaningful data, ie student ID and subject ID.

Then, final step, you loop through your data, and see if there's mark value available in using meaningful indexes.
Reply


Messages In This Thread
RE: Display Loading Image While Page Loads - by Pertti - 09-18-2018, 01:32 AM



Theme © iAndrew 2016 - Forum software by © MyBB