Hello dear developers.
I have a small problem with PHP and MySQL. So, the site is compiled with PHP, HTML and JS. I use MySQL as a database. The site is an exam site.
The problem is that the questions I write to the database through the admin panel are both written to the database and visible inside the site.
When the user looks at the tests, tests with answers given in letters work without problems. But tests whose answers are given in numbers either do not work or when you click on one answer, several answers are selected. I need the numerical answers to work normally on the site. I was using VARCHAR for answers in the database, then I changed it to TEXT. Again it doesn’t work. But let me note that the questions whose answers are written in letters work without problems. Also, I changed the answers I wrote in numbers, for example, “three” instead of 3, etc. there is no problem when writing. I only encounter such a situation when the answer is a number. I would like to note that there are questions whose numerical answers do not cause problems. So why do I have this problem in some questions and not in others?
The site is built with Bootstrap and PHP. Display of questions and selection of answers is done through JS. I also use 2 PHP files to download the questions from the database. I think there is something missing somewhere in one of them.
How to overcome this?
Please, those who know, answer.
Thanks in advance.
//action.php
<?php
require('../config.php');
if ($_GET['act'] == 'checkanswer') {
$data = $_POST;
$return_data = [];
foreach ($data as $key => $val) {
$parts = explode("_&&_", $val);
$qid = $key;
$val = $parts[0];
$aorder = $parts[1];
$sql = "SELECT correct_answer FROM mentiq WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $qid);
$stmt->execute();
$stmt->bind_result($correct_answer);
$stmt->fetch();
$stmt->close();
$result = [];
$result['true'] = ($correct_answer == $val ? 1 : 0);
$result['choosed'] = $aorder;
$result['correct'] = $correct_answer;
$result['qid'] = $qid;
$return_data[] = $result;
}
echo json_encode($return_data);
exit;
}
?>
//load_questions.php
<?php
include('../config.php');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$category_id_to_display = isset($_GET['category_id']) ? $_GET['category_id'] : 1;
$sql = "SELECT id, question, question_image, answer1, answer2, answer3, answer4, correct_answer FROM mentiq WHERE category_id = $category_id_to_display ORDER BY id";
$result = $conn->query($sql);
$questions = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questions[] = [
'id' => $row["id"],
'question' => $row["question"],
'question_image' => $row["question_image"],
'answer1' => $row["answer1"],
'answer2' => $row["answer2"],
'answer3' => $row["answer3"],
'answer4' => $row["answer4"],
'correct_answer' => $row["correct_answer"],
];
}
}
echo json_encode($questions);
$conn->close();
?>
//section in website
<section class="courses-area pt-100 pb-70">
<div class="container">
<div class="row">
<div id="questionsContainer" class="container"></div>
</div>
<script>
var currentIndex = 0;
var questions = [];
var userAnswers = {};
var answersSubmitted = false;
$(document).ready(function () {
function loadQuestions() {
$.ajax({
url: 'load_questions.php',
method: 'GET',
data: { category_id: 1 },
dataType: 'json',
success: function (data) {
questions = data;
showQuestion(currentIndex);
},
error: function (xhr, status, error) {
console.error('Error fetching questions.', status, error);
},
});
}
function showQuestion(index) {
var question = questions[index];
var answerLabels = ['A', 'B', 'C', 'D'];
var questionHtml = '<h6 class="mb-3">';
questionHtml += '<strong><label class="form-label mb-4">' + question.question + '</label></strong>';
if (question.question_image) {
questionHtml += '<br><img src="' + question.question_image + '" alt="Question Image" style="max-width:100%; height:auto;"><br>';
}
for (var i = 0; i < answerLabels.length; i++) {
var answerKey = 'answer' + (i + 1);
questionHtml += getAnswerOptionHtml(question, answerKey, answerLabels[i]);
}
questionHtml += '</div><hr class="my-4">';
$('#questionsContainer').html(questionHtml);
$('#nextBtn').prop('disabled', userAnswers[question.id] === undefined);
if (answersSubmitted) {
updateAnswerButtons();
}
}
function getAnswerOptionHtml(question, answerKey, answerLabel) {
var answerHtml = '<br><button type="button" class="btn btn-light mb-3 answer-btn left-align-btn btn5" data-answer="' + question[answerKey] + '">' + answerLabel + ') ' + question[answerKey] + '</button>';
return answerHtml;
}
function updateAnswerButtons() {
questions.forEach(function (q) {
var userAnswer = userAnswers[q.id];
var selector = '.answer-btn[data-answer="' + userAnswer + '"]';
if (userAnswer === undefined) {
return;
}
if (userAnswer === q.correct_answer) {
$(selector).removeClass('btn-light').addClass('btn-success');
} else {
$(selector).removeClass('btn-light').addClass('btn-danger');
var correctAnswerSelector = '.answer-btn[data-answer="' + q.correct_answer + '"]';
$(correctAnswerSelector).removeClass('btn-light').addClass('btn-success');
}
});
if (Object.keys(userAnswers).length === questions.length) {
showScoreToast();
}
}
function showScoreToast() {
var trueAnswers = 0;
questions.forEach(function (q) {
var userAnswer = userAnswers[q.id];
if (userAnswer === q.correct_answer) {
trueAnswers++;
}
});
var totalPoints = trueAnswers;
var totalQuestions = questions.length;
var percentage = (totalPoints / totalQuestions) * 100;
var message;
if (percentage >= 80) {
message = 'Siz <strong>' + totalQuestions + '</strong> sualdan <strong>' + totalPoints + '</strong> bal topladınız. Bu əla nəticədir. Təbrik edirik!';
} else if (percentage >= 50) {
message = 'Siz <strong>' + totalQuestions + '</strong> sualdan <strong>' + totalPoints + '</strong> bal topladınız. Bu pis nəticə deyil. Təşəkkür edirik!';
} else {
message = 'Siz <strong>' + totalQuestions + '</strong> sualdan <strong>' + totalPoints + '</strong> bal topladınız. Bu çox pis nəticədir. Yenidən cəhd edin!';
}
$('#scoreMessage').html(message);
$('#scoreToast').toast('show');
setTimeout(function () {
$('#scoreToast').toast('hide');
}, 60000);
}
$('body').on('click', '.answer-btn', function () {
var selectedAnswer = $(this).data('answer');
userAnswers[questions[currentIndex].id] = selectedAnswer;
updateAnswerButtons();
$('#nextBtn').prop('disabled', false);
});
$('#prevBtn').click(function () {
if (currentIndex > 0) {
currentIndex--;
showQuestion(currentIndex);
}
});
$('#nextBtn').click(function () {
if (currentIndex < questions.length - 1) {
currentIndex++;
showQuestion(currentIndex);
} else {
answersSubmitted = true;
updateAnswerButtons();
}
});
loadQuestions();
});
</script>
<div id="scoreToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<strong class="me-auto"><i class="fa fa-calculator fa-2x" style="color:#A93226"></i> Sizin nəticəniz</strong>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
<strong>Əziz abunəçi!</strong>
<span id="scoreMessage"></span>
</div>
</div>
<br>
<div class="btn-group mb-10" role="group" aria-label="Navigation buttons">
<button id="prevBtn" class="btn btn-warning" aria-disabled="true" style="margin-right: 10px; padding: 5px 10px;">Əvvəlki</button>
<button id="nextBtn" class="btn btn-warning" disabled style="margin-right: 10px; padding: 5px 10px;">Sonrakı</button>
<a href="../mst.php" class="btn btn-danger" style="margin-right: 10px; padding: 5px 10px;">Kateqoriyaya qayıt</a>
<button class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"><i class="fa fa-info"></i></button>
</div>
<div class="collapse mb-3" id="collapseExample">
<br>
<div class="card card-body">
<p><strong>Dəyərli abunəçi!</strong> <br>
Qeyd etmək istəyirik ki, bir suala cavab vermədən növbəti suala keçmək mümkün deyil.
Əgər siz hansısa suala səhv cavab vermisinizsə onda bu cavab qırmızı rəng və düzgün cavab isə yaşıl rəng ilə göstəriləcək.
Bu kateqoriyada olan testlərin sonunda neçə bal topladığınızı görmüş olacaqsınız. Bildirmək istəyirik ki, balların qiymətləndirilməsi hər düzgün cavaba 1 bal verilməklə hesablanır və səhv cavabların sayı qeydə alınmır.<br>
<strong>Uğurlar!</strong></p>
</div>
</div>
</div>
</section>
//MySQL table
CREATE TABLE `mentiq` (
`id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`question` text NOT NULL,
`answer1` varchar(500) NOT NULL,
`answer2` varchar(500) NOT NULL,
`answer3` varchar(500) NOT NULL,
`answer4` varchar(500) NOT NULL,
`correct_answer` varchar(500) NOT NULL,
`question_image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
Please, help me for editing files and solving this problem.
Forex Cues is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1