Good afternoon. I am starting to deal with AJAX . The code seems to work, but when you try to uncomment the line where you are working with the database, an error appears

syntax error, unexpected <

How to organize work with the database in this case? Thank!

 <? //$rawPost = file_get_contents('php://input'); $rawPost = '[{"exam":"hist1_theme1","userID":0},{"Id":7,"Mark":0},{"Id":8,"Mark":0},{"Id":9,"Mark":0},{"Id":10,"Mark":0},{"Id":11,"Mark":0},{"Id":15,"Mark":0},{"Id":33,"Mark":0},{"Id":34,"Mark":0}]'; if ($rawPost) { // Разбор пакета JSON $questsArray = json_decode($rawPost); $info = $questsArray[0]; $currExam = $db->getExamByName($info->exam); array_shift($questsArray); //$currAttempt = $db->setAttempt($info->userID, $currExam['Id']); //foreach($questsArray as $quest){ // $db->setAnswers1($quest->Mark, $currAttempt, $quest->Id); //} $response = "YES"; } else { $response = "NO"; } header('Content-type: text/plain; charset=utf-8'); header('Cache-Control: no-store, no-cache'); echo json_encode($response); 

DB class

 function __construct($params){ try { $this->_db = new PDO($params['db.conn'], $params['db.user'], $params['db.pass']); }catch(PDOException $e){ echo "Невозможно создать базу данных"; } } function __destruct(){ unset($this->_db); } protected function setDataToDB($sql){ try{ $result = $this->_db->exec($sql); }catch(PDOException $e){ echo $e->getMessage(); return false; } } protected function getDataFromDB($sql){ try{ $result = $this->_db->query($sql); $fetchFunction = function() use($result){ return $result->fetch(PDO::FETCH_ASSOC); }; return new FetchIterator($fetchFunction); }catch(PDOException $e){ echo $e->getMessage(); return false; } } function getLogins(){ $sql = "SELECT Login FROM authorization WHERE Deleted = false"; return $this->getDataFromDB($sql); } function getAuthorization($login){ $sql = "SELECT Password FROM authorization WHERE Login = '$login'"; return $this->getDataFromDB($sql)->current(); } function getUserFromDB($login){ $sql = "SELECT Id, Login FROM authorization WHERE Login = '$login'"; return $this->getDataFromDB($sql)->current(); } function setNewUser($surname, $name, $patronymic, $isMale, $email, $phone, $login, $password, $salt, $iteration, $status){ $sql = "INSERT INTO persons (Surname, Name, Patronymic, IsMale, Email, Phone) VALUES ('$surname', '$name', '$patronymic', $isMale, '$email', '$phone')"; $this->setDataToDB($sql); $id = $this->_db->lastInsertId(); $hash = createHash($password); $sql = "INSERT INTO authorization (Login, Password, Status, Id_persons) VALUES ('$login', '$hash', '$status', $id)"; $this->setDataToDB($sql); } function getRegions(){ $sql = "SELECT Id, Name FROM catalogregions WHERE Deleted = false"; return $this->getDataFromDB($sql); } //***************************** //Работа с тестами //***************************** function getQuestTypes(){ $sql = "SELECT Id, Name FROM catalogquestionstype WHERE Deleted = false"; return $this->getDataFromDB($sql); } function getQuestThemes(){ $sql = "SELECT Id, Name, Caption FROM catalogquestionstheme WHERE Deleted = false"; return $this->getDataFromDB($sql); } function getQuestThemeById($id){ $sql = "SELECT Id, Name FROM catalogquestionstheme WHERE Id = $id AND Deleted = false"; return $this->getDataFromDB($sql)->current(); } function getExamByName($examName){ $sql = "SELECT Id, Name FROM exams WHERE Name = '$examName' AND Deleted = false"; return $this->getDataFromDB($sql)->current(); } function getQuestions(){ $sql = "SELECT questions1.Id, questions1.Num_question, questions1.MarkMax, questions1.Id_exams, catalogquestionstype.Name as Type, questions1.Image_Path, questions1.Question, questions1.QuestionComment, questionskeys.Answer as RightAnswer FROM questions1 INNER JOIN questionskeys ON questionskeys.Id_questions1 = questions1.Id INNER JOIN catalogquestionstype ON catalogquestionstype.Id = questions1.Id_catalogQuestionType WHERE questions1.Deleted = false ORDER BY questions1.Id"; return $this->getDataFromDB($sql); } function setQuestion($questNum, $markMax, $examId, $imgPath, $questType, $questTheme, $quest, $questComment, $answer){ $sql = "INSERT INTO questions1 (Num_question, MarkMax, Id_exams, Image_Path, Id_catalogQuestionType, Id_catalogQuestionTheme, Question, QuestionComment) VALUES ($questNum, $markMax, $examId, '$imgPath', $questType, $questTheme, '$quest', '$questComment')"; $this->setDataToDB($sql); $newQuestID = $this->_db->lastInsertId(); $sql = "INSERT INTO questionskeys (Answer, Id_questions1) VALUES ('$answer', $newQuestID)"; $this->setDataToDB($sql); } function setAttempt($userID, $examID){ $sql = "INSERT INTO attempts (Id_persons, Id_exams) VALUES ($userID, $examID)"; $this->setDataToDB($sql); $newAttemptID = $this->_db->lastInsertId(); return $newAttemptID; } function setAnswers1($mark, $attemptID, $questionID){ $sql = "INSERT INTO answers1 (Mark, Id_attempts, Id_questions1) VALUES ($mark, $attemptID, $questionID)"; $this->setDataToDB($sql); } function setExam($name){ $sql = "INSERT INTO exams (Name) VALUES ('$name')"; $this->setDataToDB($sql); } 

The javascripta function itself looks like this:

 function sendAttempt(){ var exam = "<?=$_GET['exam'];?>"; var userID = "<?=$_SESSION['user']['Id'];?>" * 1; sendQuestsArray.unshift({exam: exam, userID: userID}); var jsonAnswers = JSON.stringify(sendQuestsArray); console.log("jsonAnswers: " + jsonAnswers); var req = getXmlHttpRequest(); req.onreadystatechange = function(){ if(req.readyState != 4) return; var otz = JSON.parse(req.responseText); console.log(otz); }; req.open("POST", "/components/sendattempt.php", true); req.setRequestHeader("Content-Type", "text/plain"); //req.setRequestHeader("Content-Length", jsonAnswers.length); req.send(jsonAnswers); } 
  • Something is not reproduced, is the problem exactly in this part of the code? - cheops
  • Yes, since when commenting all lines with db, the script is processed. - Vitaly Malkov
  • Perhaps the error is not reproduced, because the connection to the DB in another file? I just ask for the first time, I do not know what to apply. Not all the project files? - Vitaly Malkov
  • in the error is not specified file and line number? $ db :: setAttempt () is your class / method of your own, or are you using something public? I think the error is where in one of the methods setAttempt or setAnswers1, well, or in the file / class itself, well, judging by the error, or an extra sign <or short tags are prohibited <? Show what is there for the class is responsible for working with the database. - Bookin
  • @Bookin Error points to the first line. I will attach the class of the database in the answer, it does not fit here. Short tags work in all other places. - Vitaly Malkov

1 answer 1

Everything, the answer was found, all thanks who tried to help. The fact was that the function of accessing the database gave a text error with tags. And she gave the error because, as it turned out, in the php file it was necessary to reconnect all the classes to work with the database and re-create the database variable. After that, everything works.

However, this decision reminds me of a crutch. I want to ask the professionals: is there a more elegant method than re-connecting all the necessary classes?