Jeg ville totalt omstrukturere koden.
* korte funktioner
* ingen mix af HTML og logik
* ingen mix af logik og database
* og absolut ingen mix af HTML og database
Det er ikke saerligt realistisk at skriv den slags koden uden brug af framework i en enkelt PHP fil og jeg er slet ikke god til PHP.
Men til inspiration:
<?php
/*
Database setup:
CREATE TABLE quiz(
id INTEGER NOT NULL,
question VARCHAR(255) NOT NULL,
answer VARCHAR(10) NOT NULL,
PRIMARY KEY(id)
);
INSERT INTO quiz VALUES(1, 'What is 9*8', '72');
INSERT INTO quiz VALUES(2, 'What country has most citizens A) Denmark B) Sweden', 'B');
INSERT INTO quiz VALUES(3, 'Is a polar bear white yes or no', 'yes');
INSERT INTO quiz VALUES(4, 'What is the danish top level domain', '.dk');
INSERT INTO quiz VALUES(5, 'What brand is a Mondeo A) Ford B) Opel', 'A');
CREATE TABLE users (
id INTEGER NOT NULL,
name VARCHAR(32) NOT NULL,
points INT NOT NULL,
PRIMARY KEY(id)
);
INSERT INTO users VALUES(1, 'Arne', 0);
*/
// basic data structure
class Question {
public $Id;
public $Question;
public $Answer;
public $Guess;
public function __construct($id, $question, $answer) {
$this->Id = $id;
$this->Question = $question;
$this->Answer = $answer;
$this->Guess = '';
}
};
// HTML input and output
define('PAGE_TEMPLATE',
'<html>
<head>
<title>Quiz</title>
</head>
<body>
<h1>Quiz</h1>
User %s : %d points
<form method="POST">
%s
<input type="submit" value="Submit">
</form>
%s
</body>
</html>'
);
define('QUESTION_TEMPLATE',
'%s? <input type="text" name="q%d" value="%s">%s<br>'
);
function display_quiz($quiz, $user, $points, $noteempty, $footer) {
$qtxt = '';
for($i = 0; $i < count($quiz); $i++) {
$qtxt = $qtxt . sprintf(QUESTION_TEMPLATE, $quiz[$i]->Question, $quiz[$i]->Id, $quiz[$i]->Guess, $noteempty && $quiz[$i]->Guess === '' ? '<---- Fill out' : '') . "\r\n";
}
$res = sprintf(PAGE_TEMPLATE, $user, $points, $qtxt, $footer);
return $res;
}
function update_quiz($quiz) {
foreach($quiz as $q) {
if(isset($_POST['q' . $q->Id])) {
$q->Guess = $_POST['q' . $q->Id];
}
}
}
// database definition
define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', '');
define('MYSQL_DB', 'test');
// database access
function load_quiz($nquestions) {
$con = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
if(mysqli_connect_errno()) die(mysqli_connect_error());
if($stmt = $con->prepare('SELECT id, question, answer FROM quiz ORDER BY RAND() LIMIT ?')) {
$stmt->bind_param('i', $nquestions);
$stmt->execute();
$stmt->bind_result($id, $question, $correctanswer);
$res = array();
while ($stmt->fetch()) {
$res[] = new Question($id, $question, $correctanswer);
}
$stmt->close();
} else {
die($con->error);
}
$con->close();
return $res;
}
function load_points($user) {
$con = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
if(mysqli_connect_errno()) die(mysqli_connect_error());
if($stmt = $con->prepare('SELECT points FROM users WHERE name = ?')) {
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->bind_result($res);
if(!$stmt->fetch()) {
die("$user does not exist");
}
$stmt->close();
} else {
die($con->error);
}
$con->close();
return $res;
}
function add_points($delta) {
$con = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
if(mysqli_connect_errno()) die(mysqli_connect_error());
if($stmt = $con->prepare('UPDATE users SET points = points + ?')) {
$stmt->bind_param('d', $delta);
$stmt->execute();
$stmt->close();
} else {
die($con->error);
}
$con->close();
}
// business logic
function quiz_completed($quiz) {
foreach($quiz as $q) {
if($q->Guess === '') {
return false;
}
}
return true;
}
function quiz_passed($quiz) {
$correct = 0;
foreach($quiz as $q) {
if($q->Guess === $q->Answer) {
$correct++;
}
}
return $correct >= CORRECT_ANSWERS_TO_SCORE;
}
// session handling
function save_quiz($quiz) {
session_start();
$_SESSION['quiz'] = $quiz;
}
function reload_quiz() {
session_start();
return $_SESSION['quiz'];
}
// quiz definition
define('QUESTIONS_TO_SHOW', 3);
define('CORRECT_ANSWERS_TO_SCORE', 2);
// main
$user = 'Arne'; // from somewhere - out of scope of demo
if($_SERVER['REQUEST_METHOD'] === 'GET') {
$quiz = load_quiz(QUESTIONS_TO_SHOW);
echo display_quiz($quiz, $user, load_points($user), false, '');
save_quiz($quiz);
} else if($_SERVER['REQUEST_METHOD'] === 'POST') {
$quiz = reload_quiz();
update_quiz($quiz);
if(quiz_completed($quiz)) {
if(quiz_passed($quiz)) {
add_points(1);
echo display_quiz($quiz, $user, load_points($user), false, 'Passed');
} else {
echo display_quiz($quiz, $user, load_points($user), false, 'Failed');
}
} else {
echo display_quiz($quiz, $user, load_points($user), true, '');
}
} else {
die('Unknown method');
}
?>