如何改善将数据插入MySQL的PHP​​代码?

时间:2019-04-07 13:05:00

标签: php mysql mysqli

我是PHP的初学者,想知道我的函数编写是否正确。

我正在创建一个测验应用程序,并且具有以下表格:用户,课程,测验(存储prof_id,course_id和quiz_name的位置),问题,quizzes_questions和答案。请注意,一个问题可以有多个正确答案。

因此,我编写了一个脚本,用于接收测验的名称,创建该测验的教授的用户名,课程,问题,该问题的要点,答案以及该答案是否正确的参数。不是。

我的问题是我是否正确实现了它,因为我不确定使用外键。

首先,我必须从用户表中找到教授的ID,然后从课程中找到课程的ID,然后从测验中找到测验的ID,然后检查问题是否已存在于表中。根据上一次检查,如果它不存在,将其插入并插入其答案,但是如果已经存在,则选择其ID,并在特定表中插入答案。

public function insert_question($quiz_name,$professor,$course,$question,$points,$answer,$is_correct)
        {       
            $query = "select id from users where username ='$professor'";
            $result = mysqli_query($this->connection, $query);
            if(mysqli_num_rows($result)>0){
                $row=mysqli_fetch_array($result);
                $professor_id = $row['id']; 
            }else{
                $json['error'] = 'professor not found';
            }

            $query = "select id from courses where course ='$course'";
            $result = mysqli_query($this->connection, $query);
            if(mysqli_num_rows($result)>0){
                $row=mysqli_fetch_array($result);
                $course_id = $row['id'];    
            }else{
                $json['error'] = 'course not found';
            }

            $query = "select id from quizzes where professor_id ='$professor_id' and course_id = '$course_id'";
            $result = mysqli_query($this->connection, $query);
            if(mysqli_num_rows($result)>0){
                $row=mysqli_fetch_array($result);
                $quiz_id = $row['id'];          
            }else{
                $json['error'] = 'quiz not found';
            }

            $query = "select id from questions where question ='$question'";
            $result = mysqli_query($this->connection, $query);
            if(mysqli_num_rows($result)>0){
                //question already exists so we need to add its answers
                $row=mysqli_fetch_array($result);
                $question_id = $row['id'];

                $query = "insert into answers (question_id, answer, isCorrect) values ('$question_id','$answer','$is_correct')";
                $insertedA = mysqli_query($this -> connection, $query);
                if($insertedA == 1 ){
                    $jsonA['success'] = 'answer added';
                }
                else{
                    $jsonA['error'] = 'answer couldn\'t be added';
                }   

            }else if(mysqli_num_rows($result)==0){
                    //insert the actual question
                    $query = "insert into questions (question, points) values ('$question','$points')"; 
                    $insertedQ = mysqli_query($this -> connection, $query);
                    if($insertedQ == 1 ){
                        $jsonQ['success'] = 'question added';
                        $last_question_id = mysqli_insert_id($this -> connection); //id of the question i just inserted
                        echo $last_question_id;
                    }
                    else{
                        $jsonQ['error'] = 'question couldn\'t be added';
                    }


                    //insert into quizzes_questions
                    $query = "insert into quizzes_questions(quiz_id, question_id) values ('$quiz_id','$last_question_id')"; 
                    $insertedQQ = mysqli_query($this -> connection, $query);
                    if($insertedQQ == 1 ){
                        $jsonQQ['success'] = 'queestionQuizz added';
                    }
                    else{
                        $jsonQQ['error'] = 'questionQuizz couldn\'t be added';
                    }

                    $query = "insert into answers (question_id, answer, isCorrect) values ('$last_question_id','$answer','$is_correct')";
                    $insertedA = mysqli_query($this -> connection, $query);
                    if($insertedA == 1 ){
                        $jsonA['success'] = 'answer added';
                    }
                    else{
                    $jsonA['error'] = 'answer couldn\'t be added';
                    }   

                }else{
                $json['error'] = 'something wrong';
            }

                echo json_encode($json);
                echo json_encode($jsonA);
                echo json_encode($jsonQ);
                echo json_encode($jsonQQ);

                mysqli_close($this->connection);

        }

可以运行那些选择的策略来找到ID,然后像这样使用它们吗?有没有更简单的方法,因为我可能有很多脚本需要在其中查找教授的ID,所以这意味着我必须将此代码复制粘贴到每个文件中?

此外,我已经阅读了有关预准备语句的信息,我是否应该对函数中使用的每个参数都使用它们,因为它们都是用户输入的?

1 个答案:

答案 0 :(得分:-1)

首先,使用函数而不是多个if / else块。

我将mysqli_fetch_array调用放到一个单独的函数以及教授,课程和问题的单独方法中

另外,使用语句来准备(优化和保护)您的查询:https://www.php.net/manual/fr/mysqli.prepare.php

您还可以查看当前的查询构建器,例如使用它的学说,或者只是受其结构启发:https://www.doctrine-project.org/

这看起来像这样:

function fetch($query, $statements) {
   $q = mysqli_prepare($this->connection, $query);

   foreach($statements as $ statement) {
      mysqli_stmt_bind_param($q, $statement);
   }

   $res = mysqli_stmt_execute($q);
   return mysqli_num_rows($res) > 0 ? $res : null;

}

function getProfessor($professor) {
   $res = $this->fetch("select id from users where username = ? LIMIT 1", array($username));
   return $res ? mysqli_fetch_array($res)['id'] : null;
}

...

然后在您的主要功能中,您可以测试教授是否为空

 $professor = $this->getProfessor($profName);
 if (!$professor) {
   // errors
 } else {
   // succeed
 }

请记住,函数应仅实现一个目的,并且应将if / elses最小化,更不用说嵌套ifs

这是有趣的文字,解释了有关软件和Web开发的一些准则:https://en.wikipedia.org/wiki/SOLID