Home > Net >  Database connection not producing the correct output, only gives me incorrect output
Database connection not producing the correct output, only gives me incorrect output

Time:09-28

I'm try to retrieve data from a database but is keeps saying the output is way higher. I'm currently just testing it, trying to see what intellectual will produce. I want to use these values in a bar chart but I don't think I'm going about it in the most efficient way either, there's 40 questions in total.

Here is my controller

class ViewTeacherResults extends Controller
{
    public static function teacherResults() {
        $int1 = DB::table('checklist_teachers')->where('user_id', Auth::user()->name)->value('int1');
        $int2 = DB::table('checklist_teachers')->where('user_id', Auth::user()->name)->value('int2');
        $int3 = DB::table('checklist_teachers')->where('user_id', Auth::user()->name)->value('int3');
        $int4 = DB::table('checklist_teachers')->where('user_id', Auth::user()->name)->value('int4');
        $int5 = DB::table('checklist_teachers')->where('user_id', Auth::user()->name)->value('int5');

        $intellectual = $int1   $int2   $int3   $int4   $int5;
        print_r($intellectual );
        return $intellectual;
    }
}

My database, so the int1 should be printing 2 but in the results below you can see it gives 2222 for $intellectural. enter image description here enter image description here

How can I change my code to product the wanted output, and is there a more efficient way get my 40 questions results for my bar graph? bar graph will have 4 bars, int variables are all for 1 of the bars.

CodePudding user response:

I agree with CBroe that this is a design fail. But if you absolutely have to do this, then do the hard work in your Teacher Model instead.

App/Models/Teacher

public function getIntellect() { 
    return $this->int1   $this->int2   $this->int3 // continue ad nauseam
}

Then rather than use a static function, load your Teacher :

$teacher = Teacher::where('user_id', Auth::user()->name)->first();
return $teacher->getIntellect();

As a side note, why associate your Teacher with your User through their name? Just associate through the user_id as a foreign key.

CodePudding user response:

Sum your result in DB, update your class to be:

class ViewTeacherResults extends Controller
{
    return DB::table('checklist_teachers')
                ->select(DB::raw('(int1   int2   int3   int4   int5) as intellectual'))
                ->where('user_id', Auth::user()->name)
                ->value('intellectual');
}

This also will reduce the number of connections with DB which will enhance the performance.

Explanation: The reason behind having "22222" as result is that Laravel deals with "int1", "int2", "int3" ... etc as Strings.

  • Related