-
Notifications
You must be signed in to change notification settings - Fork 0
/
config - Copy backup1_11 Feb _before merge.php
1341 lines (1036 loc) · 43.5 KB
/
config - Copy backup1_11 Feb _before merge.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
session_start();
$servername = "localhost";
$dbusername = "root";
$dbpassword = "";
$database = "quiz_db";
$conn = new mysqli($servername, $dbusername, $dbpassword, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
#echo "* DB Connected<br>";
}
// Function to check if the user is logged in
function isLoggedIn() {
if (isset($_SESSION['username']) && isset($_SESSION['key'])) {
$savedUsername = $_SESSION['username'];
$savedKey = $_SESSION['key'];
global $conn;
// Retrieve the key from the database based on the username
$sql = "SELECT id, key1 FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $savedUsername);
$stmt->execute();
$stmt->bind_result($id,$keyFromDB);
if ($stmt->fetch()) {
// Check if the saved key matches the key from the database
if ($savedKey === $keyFromDB) {
return $id;
}
}
}
return false;
}
function userinfo($id, $field) {
global $conn;
// Retrieve the specified field value from the database based on the user's ID
$sql = "SELECT $field FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($value);
if ($stmt->fetch()) {
return $value;
}
return null;
}
function currenturl(){
return htmlspecialchars($_SERVER['REQUEST_URI']);
}
function changePassword($id, $newPassword) {
if ( isLoggedIn()){
global $conn;
// Hash the new password
$hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
// Update the password in the database
$sql = "UPDATE users SET password = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("si", $hashedPassword, $id);
$stmt->execute();
return $stmt->affected_rows > 0;
}
}
function insertQuestion($userId, $questionText) {
// Assuming $conn is your database connection object
global $conn;
// SQL query with placeholders, excluding quiz_id (assuming it's an auto-increment primary key)
$sql = "INSERT INTO questions (user_id, question_text) VALUES (?, ?)";
// Prepare the statement
$stmt = $conn->prepare($sql);
if (!$stmt) {
# die("Error in preparing the statement: " . $conn->error);
echo("Error in preparing the statement: " . $conn->error);
return ;
}
// Bind parameters
$questionText = htmlspecialchars($questionText, ENT_QUOTES, 'UTF-8');
$stmt->bind_param("is", $userId, $questionText);
// Execute the statement
$result = $stmt->execute();
if (!$result) {
# die("Error in executing the statement: " . $stmt->error);
echo ("Error in executing the statement: " . $stmt->error);
return ;
}
// Get the auto-generated question_id
$questionId = $stmt->insert_id;
// Close the statement
$stmt->close();
// Return the question_id
return $questionId;
}
function insertAnswer($questionId, $userId, $answerText, $isCorrect) {
// Assuming $conn is your database connection object
global $conn;
// SQL query with placeholders
$sql = "INSERT INTO answers (question_id, user_id, answer_text, is_correct) VALUES (?, ?, ?, ?)";
// Prepare the statement
$stmt = $conn->prepare($sql);
if (!$stmt) {
// Display the error message
echo "Error in preparing the statement: " . $conn->error;
// Return 0 to indicate an error
return 0;
}
// Sanitize user-generated content to prevent SQL injection
$answerText = htmlspecialchars($answerText, ENT_QUOTES, 'UTF-8');
// Bind parameters
$stmt->bind_param("iisi", $questionId, $userId, $answerText, $isCorrect);
// Execute the statement
$result = $stmt->execute();
if (!$result) {
// Display the error message
echo "Error in executing the statement: " . $stmt->error;
// Close the statement
$stmt->close();
// Return 0 to indicate an error
return 0;
}
// Get the auto-generated answer_id
$answerId = $stmt->insert_id;
// Close the statement
$stmt->close();
// Return the answer_id
return $answerId;
}
$pagefunction = [
'home' => ['homePage', 'Home'],
'add_new_question' => ['add_new_questionPage', 'AddQ'],
'view_questions' => ['viewQuestionsPage', 'Questions'],
'edit_question' => ['editQuestionPage', 'EditQ'],
'print_question_paper' => ['printQuestionPaperPage', 'Print'],
'reprint' => ['reprintQuestionPaperPage', 'Reprint'],
#'dashboard' => ['dashboardPage', 'Dashboard'],
'changepassword' => ['changePasswordPage', 'Change Password'],
'signin' => ['signinPage', 'Sign In'],
'signout' => ['signoutPage', 'Sign Out'],
// Add more pages as needed
];
headerpage();
if (isset($_GET['pagename'])){
$page = htmlspecialchars($_GET['pagename']);
if (function_exists($pagefunction[$page][0])) {
call_user_func($pagefunction[$page][0]);
} else {
echo "Invalid pagename.";
}
}else{
homePage();
}
footerpage();
function printQuestionPaperPage(){
if (!isLoggedIn()){
die("Serious Error");
}
global $conn;
// Retrieve all questions from the database
$sql = "SELECT id, question_text FROM questions ORDER BY RAND()"; // Retrieve 20 random questions for the A4 page
$result = $conn->query($sql);
$qansdataidlist = "";
if ($result->num_rows > 0) {
echo "<h2 class='text-center mb-4' style='font-size: 16px;'>MCQ Question Paper</h2>"; // Adjust font size for the title
// Add a checkbox for marking correct answers
echo "<label><input type='checkbox' id='markCorrectAnswers' onchange='toggleBoldAnswers()'> Mark Correct Answers </label> ";
echo "<label><input type='checkbox' id='correctanswerlist' onchange='togglecorrectAnswers()'> Bottom Answers</label><br><br>";
$questionCounter = 1; // Initialize question counter
$ques_ans_list = [];
// Loop through each question
while ($row = $result->fetch_assoc()) {
$questionId = $row['id'];
$questionText = $row['question_text'];
$qansdataidlist = $qansdataidlist."#". $questionId;
// Display only the question ID on the right side
echo "<div style='font-size: 11px; display: flex; justify-content: space-between;'>"; // Use flexbox for a two-column layout
echo "<div style='width: 70%;'><b>$questionCounter) $questionText</b></div>"; // Reduced font size for question text
// Move [ID:$questionId] to the right side
echo "<div style='width: 28%; text-align: right;'>[ID:$questionId]</div>";
echo "</div>";
$ques_ans_list[$questionCounter] = [];
// Retrieve and display answers for the current question
$answersSql = "SELECT id, answer_text, is_correct FROM answers WHERE question_id = ? ORDER BY RAND()";
$stmt = $conn->prepare($answersSql);
$stmt->bind_param("i", $questionId);
$stmt->execute();
$stmt->bind_result($answerId, $answerText, $isCorrect);
echo "<div style='font-size: 11px; display: flex; justify-content: space-between;'>"; // Use flexbox for a two-column layout
$index = 65; // ASCII code for 'A'
while ($stmt->fetch()) {
// Display each answer in one line with alphabetical count (A, B, C, ..., J)
$alphabeticalCount = chr($index);
// Add a class to correct answers if the checkbox is checked
$boldClass = ($isCorrect) ? 'bold-answer' : '';
if($isCorrect){
$ques_ans_list[$questionCounter][] = chr($index) ;
}
echo "<div style='width: 48%;' class='$boldClass'><span style='margin-right: 10px;'>$alphabeticalCount)</span>";
echo "$answerText</div>"; // Reduced font size for answer text
$index++;
$qansdataidlist = $qansdataidlist."@".$answerId;
}
// Add inline JavaScript to toggle bold class on correct answers
echo "</div>";
echo "<br>"; // Add a line break between questions
$questionCounter++; // Increment question counter
}
echo "<div class='correctanswerlistshow'>";
foreach ($ques_ans_list as $questionNumber => $answerNumbers) {
echo "<b> Q-$questionNumber: </b>" . implode(", ", $answerNumbers) . " ";
}
echo "</div>";
echo "<textarea class='form-control' readonly>$qansdataidlist</textarea>";
#var_dump($ques_ans_list);
echo "<script>
function toggleBoldAnswers() {
var checkbox = document.getElementById('markCorrectAnswers');
var answers = document.querySelectorAll('.bold-answer');
if (checkbox.checked) {
answers.forEach(function (answer) {
answer.style.fontWeight = 'bold';
});
} else {
answers.forEach(function (answer) {
answer.style.fontWeight = 'normal';
});
}
}
function togglecorrectAnswers() {
var checkbox = document.getElementById('correctanswerlist');
var opt = document.querySelectorAll('.correctanswerlistshow');
if (checkbox.checked) {
opt.forEach(function (opt) {
opt.style.display = 'block';
});
} else {
opt.forEach(function (opt) {
opt.style.display = 'none';
});
}
}
</script>";
} else {
echo "<p class='text-center mt-5'>No questions found.</p>";
}
}
function reprintQuestionPaperPage(){
if (!isLoggedIn()){
die("Serious Error");
}
if(!isset($_POST["reprinttext"])){
?>
<form method="post" action="<?php echo currenturl(); ?>">
<div class="form-group">
<label for="exampleTextarea">Your Textarea Label:</label>
<textarea class="form-control" name="reprinttext" id="exampleTextarea" rows="8" placeholder="Enter your text here..."></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<?php
}else{
?>
<form method="post" action="<?php echo currenturl(); ?>">
<div class="form-group">
<label for="exampleTextarea">Your Textarea Label:</label>
<textarea class="form-control" name="reprinttext" id="exampleTextarea" rows="2" placeholder="Enter your text here..."></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<?php
#echo $string = "5@20@17@19@18#4@15@13@14@16#2@5@7@6@8#1@3@1@2@4#3@12@11@9@10";
$string = htmlspecialchars($_POST['reprinttext']);
// Step 1: Split the string using #
$step1Array = explode("#", $string);
#var_dump($step1Array);
// Step 2: Initialize the final array
$finalArray = [];
// Step 3: Iterate over the results from step 1
foreach ($step1Array as $step1Item) {
// Step 4: Split each item using @
$step2Array = explode("@", $step1Item);
// Step 5: Add the resulting array to the final array
$finalArray[] = $step2Array;
}
// Display the final array
#var_dump($finalArray);
$qansdataidlist = "";
if (1==1) {
echo "<h2 class='text-center mb-4' style='font-size: 16px;'>MCQ Question Paper</h2>"; // Adjust font size for the title
// Add a checkbox for marking correct answers
echo "<label><input type='checkbox' id='markCorrectAnswers' onchange='toggleBoldAnswers()'> Mark Correct Answers </label> ";
echo "<label><input type='checkbox' id='correctanswerlist' onchange='togglecorrectAnswers()'> Bottom Answers</label><br><br>";
$questionCounter = 1; // Initialize question counter
$ques_ans_list = [];
// Loop through each question
foreach ( $finalArray as $row ) {
#while ($row = $result->fetch_assoc()) {
$questionId = $row[0];
if(getCurrentQuestionText($questionId)){
$questionText = getCurrentQuestionText($questionId);
}else{continue;}
$qansdataidlist = $qansdataidlist."#". $questionId;
// Display only the question ID on the right side
echo "<div style='font-size: 11px; display: flex; justify-content: space-between;'>"; // Use flexbox for a two-column layout
echo "<div style='width: 70%;'><b>$questionCounter) $questionText</b></div>"; // Reduced font size for question text
// Move [ID:$questionId] to the right side
echo "<div style='width: 28%; text-align: right;'>[ID:$questionId]</div>";
echo "</div>";
$ques_ans_list[$questionCounter] = [];
// Retrieve and display answers for the current question
echo "<div style='font-size: 11px; display: flex; justify-content: space-between;'>"; // Use flexbox for a two-column layout
$index = 64; // ASCII code for 'A'-1
foreach ( $row as $ansI ) {
$answerId = $ansI;
$index++;
if($index==65){continue;}
if(getCurrentAnswerDetails($answerId)){
$ansdetail = getCurrentAnswerDetails($answerId);
}else{
continue;
}
$isCorrect = $ansdetail['is_correct'];
$answerText = $ansdetail['answer_text'];
#var_dump($ansdetail);
// Display each answer in one line with alphabetical count (A, B, C, ..., J)
$alphabeticalCount = chr($index);
// Add a class to correct answers if the checkbox is checked
$boldClass = ($isCorrect) ? 'bold-answer' : '';
if($isCorrect){
$ques_ans_list[$questionCounter][] = chr($index) ;
}
echo "<div style='width: 48%;' class='$boldClass'><span style='margin-right: 10px;'>$alphabeticalCount)</span>";
echo "$answerText</div>"; // Reduced font size for answer text
$qansdataidlist = $qansdataidlist."@".$answerId;
}
// Add inline JavaScript to toggle bold class on correct answers
echo "</div>";
echo "<br>"; // Add a line break between questions
$questionCounter++; // Increment question counter
}
echo "<div class='correctanswerlistshow'>";
foreach ($ques_ans_list as $questionNumber => $answerNumbers) {
echo "<b> Q-$questionNumber: </b>" . implode(", ", $answerNumbers) . " ";
}
echo "</div>";
echo "<textarea class='form-control' readonly>$qansdataidlist</textarea>";
#var_dump($ques_ans_list);
echo "<script>
function toggleBoldAnswers() {
var checkbox = document.getElementById('markCorrectAnswers');
var answers = document.querySelectorAll('.bold-answer');
if (checkbox.checked) {
answers.forEach(function (answer) {
answer.style.fontWeight = 'bold';
});
} else {
answers.forEach(function (answer) {
answer.style.fontWeight = 'normal';
});
}
}
function togglecorrectAnswers() {
var checkbox = document.getElementById('correctanswerlist');
var opt = document.querySelectorAll('.correctanswerlistshow');
if (checkbox.checked) {
opt.forEach(function (opt) {
opt.style.display = 'block';
});
} else {
opt.forEach(function (opt) {
opt.style.display = 'none';
});
}
}
</script>";
} else {
echo "<p class='text-center mt-5'>No questions found.</p>";
}
}
}
function viewQuestionsPage(){
if (!isLoggedIn()){
die("Serious Error");
}
global $conn;
// Retrieve all questions from the database
$sql = "SELECT id, question_text FROM questions";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='container mt-4'>";
echo "<h2 class='text-center mb-4'>Question Paper</h2>";
// Loop through each question
while ($row = $result->fetch_assoc()) {
$questionId = $row['id'];
$questionText = $row['question_text'];
// Display the question with an "Edit" link
echo "<div class='card mb-4'>";
echo "<div class='card-body'>";
// Question ID and Edit button side by side
echo "<div class='d-flex justify-content-between align-items-center'>";
echo "<h5 class='card-title'>Question ID: $questionId</h5>";
echo "<a href='index.php?pagename=edit_question&id=$questionId' class='btn btn-small btn-primary'>Edit Question</a>";
echo "</div>";
echo "<p class='card-text'>$questionText</p>";
// Retrieve and display answers for the current question
$answersSql = "SELECT id, answer_text, is_correct FROM answers WHERE question_id = ?";
$stmt = $conn->prepare($answersSql);
$stmt->bind_param("i", $questionId);
$stmt->execute();
$stmt->bind_result($answerId, $answerText, $isCorrect);
echo "<div class='row'>";
while ($stmt->fetch()) {
// Display each answer in two columns
echo "<div class='col-md-6 mb-2'>";
echo "<div class='d-flex justify-content-between align-items-center'>";
echo "<p class='mb-0'>$answerText</p>";
// Display a green checkmark (✓) for correct answers
if ($isCorrect) {
echo "<span class='badge bg-success'>✓ Correct</span>";
}
echo "</div>";
echo "</div>";
}
echo "</div>";
echo "</div>";
echo "</div>";
}
echo "</div>";
} else {
echo "<p class='text-center mt-5'>No questions found.</p>";
}
}
// Function to get the current question text from the database
function getCurrentQuestionText($questionId) {
global $conn;
$sql = "SELECT question_text FROM questions WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $questionId);
$stmt->execute();
$stmt->bind_result($currentQuestionText);
if ($stmt->fetch()) {
$stmt->close();
return $currentQuestionText;
}
return null; // Handle if the question is not found
}
// Function to get the current answer details from the database
function getCurrentAnswerDetails($answerId) {
global $conn;
$sql = "SELECT answer_text, is_correct FROM answers WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $answerId);
$stmt->execute();
$stmt->bind_result($currentAnswerText, $currentIsCorrect);
if ($stmt->fetch()) {
$stmt->close();
return ['answer_text' => $currentAnswerText, 'is_correct' => $currentIsCorrect];
}
return null; // Handle if the answer is not found
}
// Function to edit a question in the database
function editQuestion($questionId, $newQuestionText) {
global $conn;
// Retrieve the current question text from the database
$currentQuestionText = getCurrentQuestionText($questionId); // Replace with your own function
// Check if the new and current values are different
if ($currentQuestionText != $newQuestionText) {
// Update the question text in the database
$sql = "UPDATE questions SET question_text = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("si", $newQuestionText, $questionId);
$stmt->execute();
// Return true even if no rows were affected
# return true;
if ($stmt->error) {
# "Error editing question: " . $stmt->error;
}
return $stmt->affected_rows > 0;
}
// Values are the same, consider it a successful update
return true;
}
// Function to edit an answer in the database
function editAnswer($answerId, $newAnswerText, $isCorrect) {
global $conn;
// Retrieve the current answer details from the database
$currentAnswerDetails = getCurrentAnswerDetails($answerId); // Replace with your own function
// Check if the new and current values are different
if ($currentAnswerDetails['answer_text'] != $newAnswerText || $currentAnswerDetails['is_correct'] != $isCorrect) {
// Update the answer text and correctness in the database
$sql = "UPDATE answers SET answer_text = ?, is_correct = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sii", $newAnswerText, $isCorrect, $answerId);
$stmt->execute();
// Return true even if no rows were affected
if ($stmt->error) {
echo "Error editing answer with ID $answerId: " . $stmt->error;
}
return $stmt->affected_rows > 0;
}
// Values are the same, consider it a successful update
return true;
}
function add_new_questionPage(){
if (!isLoggedIn()){die( "Serious Error");}
global $conn;
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
$questionText = htmlspecialchars($_POST['questionText']);
$answers = $_POST['answers']; // An array containing answer texts
$correctAnswers = isset($_POST['correctAnswers']) ? $_POST['correctAnswers'] : [];
// Insert the question into the database
$userId = isLoggedIn();
$questionId = insertQuestion($userId, $questionText);
if ($questionId) {
// Insert the answers into the database
foreach ($answers as $index => $answerText) {
if (!empty($answerText)){
$isCorrect = in_array($index, $correctAnswers) ? 1 : 0;
insertAnswer($questionId, $userId, $answerText, $isCorrect);
}else{
echo "<div class='alert alert-danger' role='alert'>Empty Answer Removed</div>";
}
}
echo "<div class='alert alert-success' role='alert'>Question and answers added successfully!</div>";
} else {
echo "Error adding question.";
}
}
// Display the form
echo "<h2>Add New Question</h2>";
echo "<form action='" . currenturl() . "' method='post'>";
echo "<div class='form-group'>";
echo "<label for='questionText'>Question Text:</label>";
echo "<textarea name='questionText' id='questionText' class='form-control' required></textarea>";
echo "</div>";
// Answer fields
for ($i = 0; $i <= 3; $i++) {
echo "<div class='form-group mb-2 mt-2'>";
echo "<div class='row align-items-center'>"; // Added 'align-items-center' class
// Input field column
echo "<div class='col-md-10 align-items-center'>";
echo "<div class='input-group'>";
echo "<input type='text' name='answers[]' id='answer$i' class='form-control answer-input'>";
echo "</div>";
echo "</div>";
// Checkbox column
echo "<div class='col-md-2 form-check align-items-center'>";
echo "<div class='form-check-input-container'>";
echo "<input class='form-check-input form-check-input-lg' type='checkbox' name='correctAnswers[]' value='$i' id='correctAnswerCheckbox$i'>";
echo "<label class='form-check-label' for='correctAnswerCheckbox$i'> Correct</label>";
echo "</div>";
echo "</div>";
echo "</div>"; // Close row
echo "</div>"; // Close form-group
}
echo "<div class='form-group mt-3'>";
echo "</div>";
echo "<button type='button' id='addAnswerField' class='btn btn-secondary'>Add Answer</button>";
#echo "<input type='text' name='answers[]' id='answer$i' class='form-control answer-input'>";
// Add JavaScript to dynamically add answer input fields
echo "<script>
document.addEventListener('DOMContentLoaded', function () {
var answerIndex = 4; // Set to the next available index
document.getElementById('addAnswerField').addEventListener('click', function () {
var newAnswerField = createAnswerField(answerIndex);
document.querySelector('.form-group.mt-3').insertAdjacentHTML('beforebegin', newAnswerField);
answerIndex++;
});
function createAnswerField(index) {
return `
<div class='form-group mb-2 mt-2'>
<div class='row align-items-center'>
<div class='col-md-10 align-items-center'>
<div class='input-group'>
<input type='text' name='answers[]' id='answer".'${index}'."' value='answer".'${index}'."' class='form-control answer-input' >
</div>
</div>
<div class='col-md-2 form-check align-items-center'>
<div class='form-check-input-container'>
<input class='form-check-input form-check-input-lg' type='checkbox' name='correctAnswers[]' value=".'${index}'." id='correctAnswerCheckbox".'${index}'."' >
<label class='form-check-label' for='correctAnswerCheckbox".'${index}'."'> Correct</label>
</div>
</div>
</div>
</div>`;
}
});
</script>";
// Add JavaScript to handle the validation styling
echo "<script>
document.addEventListener('DOMContentLoaded', function () {
// Delegate the click event to a parent element that exists when the page loads
document.addEventListener('click', function (event) {
var checkbox = event.target.closest('.form-check-input');
if (checkbox) {
var inputId = 'answer' + checkbox.value;
var inputField = document.getElementById(inputId);
if (checkbox.checked) {
inputField.classList.add('is-valid');
} else {
inputField.classList.remove('is-valid');
}
}
});
});
</script>
";
echo "<button type='submit' name='submit' class='btn btn-primary'>Add Question</button>";
echo "</form>";
}
function editQuestionPage() {
if (!isLoggedIn()) { die("Serious Error"); }
global $conn;
// Initialize $stmt
$stmt = null;
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
$newQuestionText = htmlspecialchars($_POST['questionText']);
$questionId = intval($_POST['questionId']);
// Edit the question
if (editQuestion($questionId, $newQuestionText)) {
# echo "Question edited successfully!";
echo "<div class='alert alert-success' role='alert'>Question edited successfully!</div>";
} else {
#echo "Error editing question.";
}
// Close the statement for retrieving the question text
if ($stmt) {
$stmt->close();
}
// Edit each answer
foreach ($_POST['answers'] as $index => $answerText) {
$answerId = intval($index);
$isCorrect = isset($_POST['correctAnswers'][$index]) ? 1 : 0;
if (!empty($answerText)){
if (!editAnswer($answerId, $answerText, $isCorrect)) {
# echo "Error editing answer with ID: $answerId";
}
}else{
#remove the answer
removeAnswerById($answerId);
#echo "<div class='alert alert-danger' role='alert'>Empty Answer Removed</div>";
}
}
##var_dump($_POST['newanswers']);
#var_dump($_POST['correctnewAnswers']);
$_POST['newanswers'] = isset($_POST['newanswers'])?$_POST['newanswers'] : [];
$_POST['correctnewAnswers'] = isset($_POST['correctnewAnswers'])?$_POST['correctnewAnswers'] : [];
$correctnewAnswers = $_POST['correctnewAnswers'];
##var_dump($_POST['newanswers'] );
#var_dump($_POST['correctnewAnswers'] );
foreach ($_POST['newanswers'] as $index => $answerText) {
$answerId = intval($index);
#$isCorrect = isset($_POST['correctnewAnswers'][$index]) ? 1 : 0;
$isCorrect = in_array($index, $correctnewAnswers) ? 1 : 0;
#addAnswerField
$userId = isLoggedIn();
if (!empty($answerText)){
if (!insertAnswer($questionId, $userId, $answerText, $isCorrect)) {
# echo "Error editing answer with ID: $answerId";
}
}else{
#remove the answer
#removeAnswerById($answerId);
#echo "<div class='alert alert-danger' role='alert'>Empty Answer Removed</div>";
}
}
}
// Retrieve the question details from the database
if (isset($_GET['id'])) {
$questionId = intval($_GET['id']);
$questionSql = "SELECT question_text FROM questions WHERE id = ?";
$stmt = $conn->prepare($questionSql);
$stmt->bind_param("i", $questionId);
$stmt->execute();
$stmt->bind_result($questionText);
if ($stmt->fetch()) {
// Display the form to edit the question
echo "<h2>Edit Question</h2>";
echo "<form action='" . currenturl() . "' method='post'>";#
echo "<input type='hidden' name='questionId' value='$questionId'>";
echo "<div class='form-group'>";###
echo "<label for='questionText'>Question Text:</label>";
echo "<textarea name='questionText' id='questionText' class='form-control' required>$questionText</textarea>";
echo "</div>";##form-group
// Close the statement for retrieving the question text
$stmt->close();
// Retrieve and display answers for the current question
$answersSql = "SELECT id, answer_text, is_correct FROM answers WHERE question_id = ? ORDER BY `answers`.`id` ASC";
$stmt = $conn->prepare($answersSql);
$stmt->bind_param("i", $questionId);
$stmt->execute();
$stmt->bind_result($answerId, $answerText, $isCorrect);
echo "<h3>Edit Answers</h3>";
$count_ans= 0;
while ($stmt->fetch()) {
$count_ans = $count_ans + 1;
// Display each answer with an input field
echo "<div class='form-group mb-2 mt-2'>";
echo "<div class='row align-items-center'>"; // Added 'align-items-center' class
// Input field column
echo "<div class='col-md-10 align-items-center'>";
#echo "<label for='answer$answerId' class='form-label'>Answer $answerId:</label>";
echo "<div class='input-group'>";
echo "<input type='text' name='answers[$answerId]' id='answer$answerId' class='form-control answer-input " . ($isCorrect ? "is-valid" : "") . "' value='$answerText'>";
echo "</div>";
echo "</div>";
// Checkbox column
echo "<div class='col-md-2 form-check align-items-center'>";
echo "<div class='form-check-input-container'>";
echo "<input class='form-check-input form-check-input-lg' type='checkbox' name='correctAnswers[$answerId]' value='$answerId' id='correctAnswerCheckbox$answerId' " . ($isCorrect ? "checked" : "") . ">";
echo "<label class='form-check-label' for='correctAnswerCheckbox$answerId'> Correct</label>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
echo "<div class='form-group mt-3 mb-3'>";
echo "<button type='button' id='addAnswerField' class='btn btn-secondary'>Add Answer</button>";
echo "</div>";
/* echo "<script>
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.form-check-input').forEach(function (checkbox) {
checkbox.addEventListener('change', function () {
var inputId = 'answer' + checkbox.value;
var inputField = document.getElementById(inputId);
if (checkbox.checked) {
inputField.classList.add('is-valid');
} else {
inputField.classList.remove('is-valid');
}
});
});
});
</script>"; */
echo "<script>
document.addEventListener('DOMContentLoaded', function () {
// Delegate the click event to a parent element that exists when the page loads
document.addEventListener('click', function (event) {
var checkbox = event.target.closest('.form-check-input');
if (checkbox) {
var inputId = 'answer' + checkbox.value;
var inputField = document.getElementById(inputId);
if (checkbox.checked) {
inputField.classList.add('is-valid');
} else {
inputField.classList.remove('is-valid');
}
}
});
});
</script>
";
// Add JavaScript to dynamically add answer input fields
echo "<script>
document.addEventListener('DOMContentLoaded', function () {
var answerIndex =$count_ans //0; // Set to the next available index
document.getElementById('addAnswerField').addEventListener('click', function () {
var newAnswerField = createAnswerField(answerIndex);
document.querySelector('.form-group.mt-3').insertAdjacentHTML('beforebegin', newAnswerField);
answerIndex++;
});
function createAnswerField(index) {
return `
<div class='form-group mb-2 mt-2'>
<div class='row align-items-center'>