Well im a noob so be gentle lol

Ive got a basic multiple choice quiz, and im trying to make it so that when processed it will insert the result into a table in the database. Anyone got any ideas how i should go about this?

Dani AI

Generated

Good start, . is right that there are lots of tutorials, and pointed you toward the manual — here is a short, practical plan with a ready schema and a safe insert pattern you can apply right away.

A minimal results table (use JSON for answers if your MySQL supports it, otherwise TEXT):

CREATE TABLE quiz_results (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NULL,
  quiz_id INT UNSIGNED NOT NULL,
  score SMALLINT UNSIGNED NOT NULL,
  max_score SMALLINT UNSIGNED NOT NULL,
  percentage DECIMAL(5,2) NOT NULL,
  passed TINYINT(1) NOT NULL DEFAULT 0,
  answers JSON NULL,
  time_taken INT UNSIGNED NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX (user_id),
  INDEX (quiz_id)
);

Server-side flow to implement:

  • Validate the submitted answers on the server. Never trust hidden form fields for correct answers; fetch the correct answers from your questions table and compute the score server-side.
  • Use prepared statements (PDO or MySQLi) to insert the result. Example pattern with PDO:
$pdo = new PDO('mysql:host=localhost;dbname=quizdb;charset=utf8mb4', 'user', 'pass', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$stmt = $pdo->prepare("INSERT INTO quiz_results (user_id, quiz_id, score, max_score, percentage, passed, answers, time_taken) VALUES (:user_id, :quiz_id, :score, :max_score, :percentage, :passed, :answers, :time_taken)");

$stmt->execute([
  ':user_id' => $userId,
  ':quiz_id' => $quizId,
  ':score' => $score,
  ':max_score' => $max,
  ':percentage' => $percentage,
  ':passed' => $passed ? 1 : 0,
  ':answers' => json_encode($answers),
  ':time_taken' => $timeTaken
]);

Key cautions and tips:

  • Use prepared statements to avoid SQL injection (see OWASP guidance: SQL Injection Prevention Cheat Sheet).
  • Protect the form with a CSRF token and validate input types.
  • If you allow multiple attempts, add an attempt_number or record IP/anon token.
  • If you need DB docs for table/data types, see MySQL docs: CREATE TABLE.
  • For debugging, check DB user permissions, catch PDO exceptions, and log the SQL error message (not to the user).

Recommended Answers

All 2 Replies

This is very basic PHP/MySQL. There are a million tutorials online explaining this. Just do a quick search on Google and you find a TON of examples with sample code.

Take a look at php.net's function list for your database system. They'll have examples and discussion there, too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.