简体   繁体   English

如何改进我的 PHP 代码以将数据插入 MySQL?

[英]How can I improve my PHP code to insert data into MySQL?

I am a beginner in PHP and want to know if my function is written well.我是 PHP 初学者,想知道我的函数是否写得好。

I am creating a quiz application and have the following tables: users, courses, quizzes (where the prof_id, course_id and quiz_name are stored), questions, quizzes_questions, answers.我正在创建一个测验应用程序并有以下表格:用户、课程、测验(存储 prof_id、course_id 和 quiz_name)、问题、quizzes_questions、答案。 Note that a question can have more than one correct answer.请注意,一个问题可以有多个正确答案。

So, I wrote a script that receives as parameters the name of the quiz, the username of the professor that created it, the course, the question, the points of that question, the answer, and whether that answer is correct or not.因此,我编写了一个脚本,该脚本接收测验名称、创建它的教授的用户名、课程、问题、该问题的要点、答案以及该答案是否正确作为参数。

My question is if I have implemented it correctly, as I am not really sure about using foreign keys.我的问题是我是否正确实现了它,因为我不确定是否使用外键。

First, I have to find the id of the professor from the users table, then the id for the course from courses, then id for quiz from quizzes, and then check if the question already exists in the table.首先,我必须从 users 表中找到教授的 id,然后从课程中找到课程的 id,然后从测验中找到测验的 id,然后检查问题是否已经存在于表中。 Based on the last check, I insert it if it does not already exist, along with its answers, but if it already exists, I select the id of it and do the insertion of the answers in the specific table.根据上次检查,如果它不存在,我会插入它及其答案,但如果它已经存在,我选择它的 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);

        }

Is it ok to run those select stataments to find the ids and then use them like that?可以运行那些 select stataments 来查找 ids 然后像这样使用它们吗? Is there an easier way to do that as I might have many scripts in which I have to find the id of the professor, so that means I would have to copy-paste this code in each file?有没有更简单的方法来做到这一点,因为我可能有很多脚本,我必须在其中找到教授的 ID,所以这意味着我必须将此代码复制粘贴到每个文件中?

Also, I've read about prepared statements, should I use them for every parameter I have in my function, as all of them are user-inputted?另外,我已经阅读了准备好的语句,我是否应该将它们用于函数中的每个参数,因为它们都是用户输入的?

First and foremost, use functions instead of multiple if/else blocks.首先,使用函数而不是多个 if/else 块。

I'd put the mysqli_fetch_array call into a separate function as well as separate methods for professor, course and questions我会将mysqli_fetch_array调用放入一个单独的函数以及教授、课程和问题的单独方法中

Also, use statements to prepare (optimize and secure) your queries : https://www.php.net/manual/fr/mysqli.prepare.php此外,使用语句来准备(优化和保护)您的查询: https : //www.php.net/manual/fr/mysqli.prepare.php

You can also have a look at current query builders such as doctrine to use it or just get inspired by its structure : https://www.doctrine-project.org/您还可以查看当前的查询构建器,例如使用它的学说或只是从其结构中获得启发: https : //www.doctrine-project.org/

That would look like something like this :那看起来像这样:

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;
}

...

then in your main function you can just test if professors isn't null然后在您的主要功能中,您可以测试教授是否为空

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

Remember that functions should only fulfill one purpose and you should minimize if/elses, let alone nested ifs请记住,函数应该只实现一个目的,并且应该最小化 if/else,更不用说嵌套的 if

Here's an interesting text explaining some guidelines on software and web development : https://en.wikipedia.org/wiki/SOLID这是一段有趣的文字,解释了一些软件和 Web 开发指南: https : //en.wikipedia.org/wiki/SOLID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM