-1

Since I'm new to PHP I don't have much idea about this following error. Someone told me to downgrade my PHP Version 7.2 to 7.0 but still this problem is existing and causing 500 Internal Error.

Uncaught Error: Using $this when not in object context in /home/e61fff4mjhlu/public_html/tcs2/wp-content/plugins/Addquestions/Model/Exam.php:56

Here's how Line 56 code looks like in Exam.php :

$sql="SELECT `ExamMaxquestion`.`subject_id`,`ExamMaxquestion`.`max_question` from `".$this->wpdb->prefix."emp_exam_maxquestions` AS `ExamMaxquestion` where `ExamMaxquestion`.`exam_id`=".$id;

Exam.php full code :-

 <?php
$dir = plugin_dir_path(__FILE__);
class Exam extends ExamApps
{
    public function validate($post)
    {
        $gump = new GUMP();
        $post=$this->globalSanitize($post); // You don't have to sanitize, but it's safest to do so.
        $gump->validation_rules(array(
                'name'    => 'required|alphaNumericCustom',
                'passing_percent'    => 'required|numeric',
                'duration'    => 'required|numeric',
                'attempt_count'    => 'required|numeric',
                'start_date'    => 'required|date',
                'end_date'    => 'required|date'

                ));
        $gump->filter_rules(array(
                'name' => 'trim'
                ));
        $validatedData = $gump->run($post);
        GUMP::set_field_name("name", "Group Name");
        return array('validatedData'=>$validatedData,'error'=>$gump->get_readable_errors(true));
    }    
    public function examStats($id)
    {
        $sql="SELECT `Exam`.`id`,`Exam`.`name`,`Exam`.`start_date`,`Exam`.`end_date`,`Exam`.`passing_percent` from `".$this->wpdb->prefix."emp_exams` AS `Exam` INNER JOIN `".$this->wpdb->prefix."emp_exam_groups` AS `ExamGroup` ON (`Exam`.`id`=`ExamGroup`.`exam_id`) WHERE `Exam`.`status`='Closed' and `Exam`.`id`=".$id;
        $this->autoInsert->iFetch($sql,$examvalue);
        $examStats=array();
        $examStats['Exam']['id']=$examvalue['id'];
        $examStats['Exam']['name']=$examvalue['name'];
        $examStats['Exam']['start_date']=$examvalue['start_date'];
        $examStats['Exam']['end_date']=$examvalue['end_date'];
        $examStats['OverallResult']['passing']=(float) $examvalue['passing_percent'];
        $examStats['OverallResult']['average']=(float) $this->studentAverageResult($examvalue['id']);
        $examStats['StudentStat']['pass']=$this->studentStat($examvalue['id'],'Pass');
        $examStats['StudentStat']['fail']=$this->studentStat($examvalue['id'],'Fail');
        $examStats['StudentStat']['absent']=$this->examTotalAbsent($examvalue['id']);
        return$examStats;
    }
    public function examAttendance($id,$type)
    {
        $examStats=array();
        $examStats=$this->studentStat($id,$type,'all');
        return$examStats;
    }
    public function examAbsent($id)
    {
      $examStats=array();
      $examStats=$this->examTotalAbsent($id,'all');
      return$examStats;
    }
    public function totalMarks($id)
    {
        $limit=0;
        $sql="SELECT `ExamMaxquestion`.`subject_id`,`ExamMaxquestion`.`max_question` from `".$this->wpdb->prefix."emp_exam_maxquestions` AS `ExamMaxquestion` where `ExamMaxquestion`.`exam_id`=".$id;
        $this->autoInsert->iWhileFetch($sql,$examMaxQuestionArr);
        $totalMarks=0;
        if($examMaxQuestionArr)
        {
          foreach($examMaxQuestionArr as $value)
          {
            $quesNo=$value['max_question'];
            $subjectId=$value['subject_id'];
            if($quesNo==0)
            $limit=" ";
            else
            $limit=' LIMIT '.$quesNo;
            $sqlExamQuestion="select sum(`marks`) AS `total_marks` from (select `Question`.`marks` FROM `".$this->wpdb->prefix."emp_exam_questions` AS `ExamQuestion` Inner JOIN `".$this->wpdb->prefix."emp_questions` AS `Question` ON (`ExamQuestion`.`question_id`=`Question`.`id`) WHERE `ExamQuestion`.`exam_id`=".$id." AND `Question`.`subject_id`=".$subjectId.$limit.") AS `ExamQuestion`";
            $this->autoInsert->iFetch($sqlExamQuestion,$totalMarksArr);
            $totalMarks=$totalMarks+$totalMarksArr['total_marks'];
        }
    }
    else
    {
        $sql="SELECT SUM(`Question`.`marks`) AS `total_marks` from `".$this->wpdb->prefix."emp_exam_questions` AS `ExamQuestion` Inner JOIN `".$this->wpdb->prefix."emp_questions` AS `Question` ON (`Question`.`id`=`ExamQuestion`.`question_id`) where `ExamQuestion`.`exam_id`=".$id;
        $this->autoInsert->iFetch($sql,$totalMarksArr);
        $totalMarks=$totalMarksArr['total_marks'];
    }    
    return$totalMarks;
  }    
}
?>
Shaym Murmu
  • 3
  • 1
  • 7
  • Seems that you are trying to call `$this` outside of the class. I guess, you need something like `global $wpdb;` before the query and replace `$this->wpdb->prefix` to `$wpdb->prefix`. More accurate answer will appear if you show more code. – user1597430 Jun 13 '19 at 19:31
  • 4
    Possible duplicate of [PHP Fatal error: Using $this when not in object context](https://stackoverflow.com/questions/2350937/php-fatal-error-using-this-when-not-in-object-context) – Patrick Q Jun 13 '19 at 19:31
  • I found a configuration.php file, this might help you to go through the more the details.function __construct() { global $wpdb; $this->wpdb=$wpdb; $this->tableName=$wpdb->prefix."emp_configurations"; $this->ExamApp = new ExamApps(); $this->configuration=$this->ExamApp->configuration(); $this->Configuration = new Configuration(); $this->autoInsert=new autoInsert(); $this->ajaxUrl=admin_url('admin-ajax.php').'?action=examapp_Configuration'; $this->url=admin_url('admin.php').'?page=examapp_Configuration'; } – Shaym Murmu Jun 13 '19 at 19:52
  • I would consider this code fairly advanced for someone who says they are "new to PHP". Did you actually write the code that's in the body of your question or is this some plugin that you downloaded that isn't working? – Patrick Q Jun 13 '19 at 20:00
  • @PatrickQ Yes, this is actually a plugin which I downloaded and some function of this is not working. – Shaym Murmu Jun 14 '19 at 02:08
  • @ShaymMurmu Then I suggest you contact the author of the plugin. There could be errors like this throughout the code and it may not be a simple fix for someone without much experience. – Patrick Q Jun 14 '19 at 11:51
  • @PatrickQ, I downgraded my PHP version from 7.1 to 5.6 and actually it worked. – Shaym Murmu Jun 14 '19 at 20:48

2 Answers2

0

$this is used within objects to refer to itself. It looks like you are trying to use it outside of an object. In this context, you should reference the global wpdb prefix like so:

global $wpdb;
$sql = "SELECT ExamQuestion.subject_id, ExamQuestion.max_question FROM ".$wpdb->prefix."emp_exam_maxquestions AS ExamQuestion WHERE ExamMaxquestion.exam_id=".$id;
Typel
  • 1,109
  • 1
  • 11
  • 34
0

$this appears to refer to the wordpress database prefix for your tables. Typically your tables will be named xxx_tablename -- the xxx is a prefix you defined when you installed WP. $this as a variable is typically found in a function where the $this variable has been defined in class. If you copied the code from some function, go back and figure out how the table name was being passed, and change the $this variable to the table name prefix -- or just hard code it in with your prefix:

FROM `myprefix_emp_exam_maxquestions` 

However, if you're new to PHP and trying to do this, you will probably find that you have other problems related to the use of $this -- you just found the first one. FYI, your problem will exist in practically any version of PHP. The downgrade to 7.0 didn't have anything to do with it.

nemonoman
  • 1
  • 1
  • @nemonaman Thanks, I tried this method. For experiment purpose, I used this $wpdb='mydbname'; $this=$wpdb. It actually worked to some extent. I again thought about downgrading my PHP version to 5.6 and it worked all those php error were gone. I guess there was some syntax compatibility issue with Newer PHP version . Anyway it worked for me. Now later on , i'll try to learn what was actually cause with PHP documentation . If you any resources to share, i would love to go through them. – Shaym Murmu Jun 14 '19 at 20:54