Добрый день
Начинаю разбираться с AJAX
. Код вроде работает, но при попытке раскомментировать строку, где идет работа с базой данных, появляется ошибка:
syntax error, unexpected <
Как организовать работу с БД в этом случае? Спасибо!
<?
//$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);
Класс БД
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);
}
Сама функция javascripta выглядит так:
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);
}