PHP PDO MySQL Project: Build a Student Marks List

Level: Intermediate
Time to read: 15 minutes
Track: AI with PHP · Foundations

A class teacher at Shree Vidya Tuition Centre, Pune, keeps term marks in a notebook: roll number, student name, subject, and a score out of 100. That works for one batch. It becomes messy when parents ask, “What did Rahul Iyer score in Science?” The better next step is a small table you can query from PHP.

This project shows how to connect PHP to MySQL with PDO (PHP Data Objects), insert marks with prepared statements, and print the list as HTML without accidentally turning a name into code. You will leave with a script you can adapt to any simple register — attendance, fees, or invoices — not only marks. That register is also the right source of facts if you later add an AI summary: the model should phrase a sentence about Rahul’s Science mark, not invent the score.

Key takeaways

  • PDO connects PHP to MySQL with a DSN, a user, a password, and safe default options.
  • Prepared statements with placeholders such as :student_name keep values out of the SQL text.
  • Print every name and roll number with htmlspecialchars($value, ENT_QUOTES, 'UTF-8').
  • The same PHP logic can be tested with SQLite; only the DSN and CREATE TABLE change for MySQL.
  • When you add AI later, read marks from this table and put them in the prompt — do not let the model invent scores.

What you will build

A page that lists rows like these:

  • R12 — Ananya Sharma — Mathematics — 88
  • R12 — Ananya Sharma — Science — 91
  • R15 — Rahul Iyer — Mathematics — 74
  • R15 — Rahul Iyer — Science — 69
  • R18 — Meera Patel — Mathematics — 95

The same student can appear more than once, once per subject. We will not build a login or an edit form in this lesson. The goal is a correct, safe round trip: connect, insert, select, display.

Why PDO, and why prepared statements

PHP can talk to MySQL in more than one way. PDO is the one to learn now because the same style of code also works with other databases, and because prepared statements are a natural part of it.

A prepared statement sends the SQL with placeholders such as :roll_no, then sends the values separately. The database never treats those values as SQL. That is the standard defence against SQL injection. If a mischievous value arrived in a name field, it would be stored as text, not executed as a command.

Do not build queries by gluing strings together:

// Do not do this
$sql = "INSERT INTO marks (student_name) VALUES ('" . $name . "')";

Even if today’s form is only used by a teacher, the habit is hard to undo later. Use placeholders from the first insert.

Create the database and table

In MySQL, create a database and a table. You can run this in any MySQL client your host provides.

CREATE DATABASE tuition_centre CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE tuition_centre;

CREATE TABLE marks (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    roll_no VARCHAR(20) NOT NULL,
    student_name VARCHAR(100) NOT NULL,
    subject VARCHAR(50) NOT NULL,
    marks TINYINT UNSIGNED NOT NULL,
    CHECK (marks <= 100)
);

utf8mb4 is the character set you want for Indian names and for the rupee sign in later projects. The CHECK clause (supported on modern MySQL 8) rejects a mark such as 150.

Connect with PDO

Store the database user and password in environment variables, not in the file you will later commit to git. A DSN (Data Source Name) tells PDO which driver, host, database, and character set to use.

<?php
declare(strict_types=1);

$dsn = 'mysql:host=127.0.0.1;dbname=tuition_centre;charset=utf8mb4';
$user = getenv('DB_USER');
$pass = getenv('DB_PASS');

if ($user === false || $user === '') {
    exit('Set the DB_USER and DB_PASS environment variables.');
}

$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
]);

Three options are worth setting every time:

  • ERRMODE_EXCEPTION turns SQL failures into exceptions, so a typo in a table name does not fail silently.
  • FETCH_ASSOC gives you rows as arrays named by column, such as $row['student_name'].
  • EMULATE_PREPARES => false asks the database to use real prepared statements rather than a PHP imitation.

Use 127.0.0.1 when MySQL is on the same machine. On shared hosting the host name is often something your control panel shows, not localhost. The DSN shape stays the same: mysql:host=...;dbname=...;charset=utf8mb4.

Insert rows with a prepared statement

function addMark(PDO $pdo, string $rollNo, string $name, string $subject, int $marks): void
{
    $sql = 'INSERT INTO marks (roll_no, student_name, subject, marks)
            VALUES (:roll_no, :student_name, :subject, :marks)';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':roll_no'      => $rollNo,
        ':student_name' => $name,
        ':subject'      => $subject,
        ':marks'        => $marks,
    ]);
}

addMark($pdo, 'R12', 'Ananya Sharma', 'Mathematics', 88);
addMark($pdo, 'R12', 'Ananya Sharma', 'Science', 91);
addMark($pdo, 'R15', 'Rahul Iyer', 'Mathematics', 74);
addMark($pdo, 'R15', 'Rahul Iyer', 'Science', 69);
addMark($pdo, 'R18', 'Meera Patel', 'Mathematics', 95);

prepare() compiles the statement once; execute() fills in the values. Named placeholders are easy to read. You can also use ? and pass a list of values, but names scale better as queries grow.

For a one-off lesson you may call addMark() at the top of the script. In a real page you would run inserts only when a teacher submits a form, and you would also validate that marks are between 0 and 100 in PHP before you touch the database.

Select the list and print safe HTML

Reading is simpler because this query has no user values, so $pdo->query() is fine. The moment you filter by roll number or subject from a form, switch back to prepare().

$stmt = $pdo->query(
    'SELECT roll_no, student_name, subject, marks
     FROM marks
     ORDER BY roll_no, subject'
);
$rows = $stmt->fetchAll();

Then print a table. Names belong to people, but they still must be escaped. htmlspecialchars turns < and & into text so a strange name cannot break your page or inject a script tag.

echo "<table>\n";
echo "<tr><th>Roll no.</th><th>Name</th><th>Subject</th><th>Marks</th></tr>\n";

foreach ($rows as $row) {
    echo "<tr>";
    echo "<td>" . htmlspecialchars($row['roll_no'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . htmlspecialchars($row['student_name'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . htmlspecialchars($row['subject'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . htmlspecialchars((string) $row['marks'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "</tr>\n";
}

echo "</table>\n";

Always pass ENT_QUOTES and 'UTF-8' so both single and double quotes are encoded and Indian names stay intact. Prepared statements protect the database. htmlspecialchars protects the page. You need both; they solve different problems.

Try this

Add a sixth row for Meera Patel in Science, with a mark of 90, then refresh. You should see six lines, still ordered by roll number. Then temporarily insert a name that contains <b>Test</b>. In the HTML source of the page you should see &lt;b&gt;Test&lt;/b&gt;, and the browser should show the characters <b>Test</b> rather than a bold word. If the word is bold, the escape step is missing.

How this was tested (SQLite vs MySQL)

The insert, select, table rendering, and htmlspecialchars logic were run with PHP 8.4 using an in-memory SQLite database, because the machine that checked this lesson did not have MySQL. The behaviour you care about — placeholders, fetching associative rows, and escaped output — is the same.

The parts that differ if you copy the test approach:

  • DSN. MySQL: mysql:host=127.0.0.1;dbname=tuition_centre;charset=utf8mb4 plus a username and password. SQLite: sqlite::memory: (or sqlite:/path/to/file.sqlite) with no user or password.
  • Schema. MySQL uses INT UNSIGNED AUTO_INCREMENT and VARCHAR. SQLite uses INTEGER PRIMARY KEY and TEXT. The column names can stay identical so the PHP does not change.
  • Driver. Production for this project is MySQL, which is what most Indian shared hosts offer. SQLite is excellent for tests and for a tiny local prototype.

When you deploy on a host, use the MySQL DSN and credentials from the host’s panel, still via environment variables or a config file kept outside the web root.

What you learned

  • PDO connects PHP to MySQL with a DSN, a user, a password, and a few safe default options.
  • Prepared statements with placeholders such as :student_name keep values out of the SQL text.
  • A marks table can store several rows per student, one per subject, and a query can order them for display.
  • htmlspecialchars($value, ENT_QUOTES, 'UTF-8') is required before you print any text into HTML, including names and roll numbers.
  • The same PHP logic can be tested with SQLite; only the DSN and the CREATE TABLE details need to change for MySQL.

Quick quiz

  1. 1. Why should you use a placeholder such as :student_name instead of gluing the name into the SQL string?

    • A) Placeholders make the query run faster on every host
    • B) Values stay separate from the SQL, which is the standard defence against SQL injection
    • C) MySQL does not allow quotes in names otherwise
    Show answer

    B. A prepared statement sends the SQL and the values separately. The database will not treat a strange name as a command.

  2. 2. You print $row['student_name'] straight into an HTML table. What is missing?

    • A) htmlspecialchars($row['student_name'], ENT_QUOTES, 'UTF-8')
    • B) A second database query
    • C) number_format()
    Show answer

    A. Prepared statements protect the database. Escaping protects the page. You need both.

  3. 3. Which DSN is the production MySQL form used in this lesson?

    • A) sqlite::memory:
    • B) mysql:host=127.0.0.1;dbname=tuition_centre;charset=utf8mb4
    • C) https://phptutorial.co.in/mysql
    Show answer

    B. SQLite in-memory is only for tests on a machine without MySQL. Production uses the MySQL DSN, plus a user and password from the environment.

  4. 4. You want an AI sentence about Rahul Iyer’s Science mark. Where should the number 69 come from?

    • A) The model’s best guess
    • B) The marks table, then you place “69” in the prompt yourself
    • C) A hardcoded string in the prompt template forever
    Show answer

    B. Official scores live in your database. The model can write the prose once you have supplied the fact. (C is brittle as soon as the mark changes.)

Next lesson

Next in the intermediate track, take the same marks table and add insert, update, and delete from a small form, still with prepared statements. After that you can filter by roll number or subject. The later invoice project reuses this exact pattern: a PDO connection, placeholders, and escaped output — only the columns change, from marks to rupee amounts.