Skip to content · ⁨Bỏ qua nội dung⁩

GAC017 Computing III: Data Science and Web Apps · ⁨GAC017 Tin học III: Khoa học Dữ liệu và Ứng dụng Web⁩

GAC Computing · ⁨Tin học GAC⁩ · Topic 3 · ⁨Chủ đề 3⁩

3.1

What this module is, and how it is marked · ⁨Mô-đun này là gì và cách chấm điểm⁩

English

GAC017 is the Level III computing module: what sits behind a website. Six units cover back-end JavaScript, databases, SQL, connecting the two, and a first look at data science.

Assessment is entirely practical — a database 数据库 you design and build, a web app 网络应用 that talks to it, a data analysis project 数据分析项目, and coursework — usually spread across most of the semester rather than concentrated at the end.

  • The work is judged on whether it runs and answers a question, not on how much code there is.
  • ⚠ Design the database before you write a query. Almost every problem later is a table problem wearing a query's clothes.

Every SQL example here runs in the site's own code playground, and the SQL reference there is the fuller version of these notes.

Tiếng Việt

GAC017 là mô-đun máy tính cấp III: những gì nằm phía sau một trang web. Sáu đơn vị học phần bao gồm back-end, JavaScript, cơ sở dữ liệu, SQL, kết nối hai loại này, và cái nhìn đầu tiên về khoa học dữ liệu.

Đánh giá hoàn toàn mang tính thực hành — một cơ sở dữ liệu bạn thiết kế và xây dựng, một ứng dụng web giao tiếp với nó, một dự án phân tích dữ liệu, và bài tập trên lớp — thường là phân bổ trong suốt hầu hết học kỳ thay vì tập trung vào cuối khóa.

  • Công việc được đánh giá dựa trên việc nó chạy được và trả lời được câu hỏi, không phải dựa vào lượng code có bao nhiêu.
  • ⚠ Thiết kế cơ sở dữ liệu trước khi viết truy vấn. Hầu như mọi vấn đề sau này đều là vấn đề về bảng. đang mặc bộ quần áo của một truy vấn.

Mỗi ví dụ SQL ở đây đều chạy trong sân chơi code riêng của trang web, và tài tham khảo SQL tại đó là phiên bản đầy đủ hơn của những ghi chú này.

Vocabulary · ⁨Từ vựng⁩ Train · ⁨Luyện tập⁩
English Tiếng Việt
database/ˈdeɪtəbeɪs/ cơ sở dữ liệu
web app/web æp/ ứng dụng web
data analysis project/ˈdeɪtə əˈnæləsɪs ˈprɒdʒekt/ dự án phân tích dữ liệu
front end/frʌnt end/ giao diện trước
back end/bæk end/ backend
SQL/ˌes kjuː ˈel/ SQL
3.1

JavaScript for a web app's back end · ⁨JavaScript cho phần máy chủ của ứng dụng web⁩

Syllabus · ⁨Chương trình⁩
English

Unit 1 of 6 in GAC017 Computing III: Data Science and Web Apps (Level III). The module is taught over about 40 class hours plus 20 hours of independent study, and is assessed at the teaching centre and moderated by ACT — there is no external exam.

Module purpose: On completion of this module, students should be able to create a web app. Students will learn about back- end programming and how to create a dynamic website. They will be able to use SQL to analyze data from multiple tables in order to make informed decisions.

The module outcomes this unit works towards:

Learning Objective GAC017.1: Understand the basic components of a Web Application.

Tiếng Việt

Đơn vị 1 trong số 6 đơn vị của GAC017 Computing III: Data Science and Web Apps (Level III). Mô-đun được giảng dạy trong khoảng 40 giờ học trên lớp cộng thêm 20 giờ tự học, và được đánh giá tại trung tâm giảng dạy với sự giám sát của ACT — không có kỳ thi bên ngoài.

Mục đích mô-đun: Sau khi hoàn thành mô-đun này, sinh viên sẽ có khả năng tạo một ứng dụng web. Sinh viên sẽ tìm hiểu về lập trình back-end và cách tạo một website động. Họ sẽ có thể sử dụng SQL để phân tích dữ liệu từ nhiều bảng nhằm đưa ra các quyết định sáng suốt.

Các kết quả học tập mà đơn vị này hướng tới:

Mục tiêu học tập GAC017.1: Hiểu các thành phần cơ bản của Ứng dụng Web.

Source: Cambridge International syllabus · ⁨Nguồn: Chương trình Cambridge International⁩

English
  • The front end 前端 runs in the browser; the back end 后端 runs on a server and holds what the browser must not.
  • A server 服务器 receives a request 请求 and returns a response 响应. That loop is the whole architecture.
  • An API 应用程序接口 is the agreed shape of those requests and responses.
  • ⚠ Anything secret — a password, a key — belongs on the back end only. Code in a browser is readable by everyone who visits.
Tiếng Việt
  • Phần client chạy trên trình duyệt; phần server chạy trên máy chủ và lưu giữ những gì trình duyệt cần.
  • Một máy chủ nhận một yêu cầu và trả về một phản hồi. Chu trình lặp đó chính là toàn bộ kiến trúc.
  • Một API là định dạng thống nhất của các yêu cầu và phản hồi đó.
  • ⚠ Mọi thứ bí mật — mật khẩu, khóa — chỉ nên nằm ở phần máy chủ. Code trong trình duyệt là có thể đọc được bởi tất cả mọi người truy cập.
Vocabulary · ⁨Từ vựng⁩ Train · ⁨Luyện tập⁩
English Tiếng Việt
server/ˈsɜːvə/ máy chủ
request/rɪˈkwest/ yêu cầu
response/rɪˈspɒns/ phản ứng
API/ˌeɪ piː ˈaɪ/ API
3.2

Back-end programming · ⁨Lập trình phần máy chủ⁩

Syllabus · ⁨Chương trình⁩
English

Unit 2 of 6 in GAC017 Computing III: Data Science and Web Apps (Level III). The module is taught over about 40 class hours plus 20 hours of independent study, and is assessed at the teaching centre and moderated by ACT — there is no external exam.

The module outcomes this unit works towards:

Learning Objective GAC017.2: Adapt a back-end application using scripting languages to interact with databases.

Tiếng Việt

Đơn vị 2 trong số 6 đơn vị của GAC017 Computing III: Data Science and Web Apps (Level III). Mô-đun được giảng dạy trong khoảng 40 giờ học trên lớp cộng thêm 20 giờ tự học, và được đánh giá tại trung tâm giảng dạy với sự giám sát của ACT — không có kỳ thi bên ngoài.

Các kết quả học tập mà đơn vị này hướng tới:

Mục tiêu học tập GAC017.2: Tùy chỉnh ứng dụng back-end sử dụng ngôn ngữ lập trình script để tương tác với cơ sở dữ liệu.

Source: Cambridge International syllabus · ⁨Nguồn: Chương trình Cambridge International⁩

English
  • A route 路由 maps a URL to code that runs when that URL is requested.
  • Validate input 校验输入 on the server. Checking in the browser is a convenience for honest users, not a defence.
  • Never build a query by joining strings with user input. That is how SQL injection SQL 注入 happens, and it is the security failure this unit exists to prevent.
  • Return an honest status: 200 for success, 400 for a bad request, 404 for something that is not there.
Tiếng Việt
  • Một route (tuyến) ánh xạ một URL với đoạn code sẽ chạy khi URL đó được yêu cầu.
  • Xác thực đầu vào trên máy chủ. Kiểm tra trên trình duyệt chỉ là tiện ích cho người dùng chân thành, chứ không phải là biện pháp phòng thủ.
  • Không bao giờ xây dựng truy vấn bằng cách nối chuỗi với đầu vào của người dùng. Đó chính là cách xâm nhập SQL SQL xảy ra, và đó là lỗ hổng bảo mật mà đơn vị học này nhằm ngăn chặn.
  • Trả về một trạng thái trung thực: 200 cho thành công, 400 cho yêu cầu sai, 404 cho điều gì đó không tồn tại.
Vocabulary · ⁨Từ vựng⁩ Train · ⁨Luyện tập⁩
English Tiếng Việt
route/ruːt/ đường đi
Validate input/ˈvælɪdeɪt ˈɪnpʊt/ Xác thực dữ liệu đầu vào
SQL injection/ˌes kjuː ˈel ɪnˈdʒekʃn/ Inject SQL
relational database/rɪˈleɪʃənl ˈdeɪtəbeɪs/ cơ sở dữ liệu quan hệ
tables/ˈteɪblz/ bảng
primary key/ˈpraɪməri kiː/ khóa chính
foreign key/ˈfɒrən kiː/ khóa ngoại
Normalisation/ˌnɔːməlaɪˈzeɪʃn/ Chuẩn hóa (Normalisation)
entities/ˈentɪtiz/ thực thể
3.3

Introduction to databases · ⁨Giới thiệu về cơ sở dữ liệu⁩

Syllabus · ⁨Chương trình⁩
English

Unit 3 of 6 in GAC017 Computing III: Data Science and Web Apps (Level III). The module is taught over about 40 class hours plus 20 hours of independent study, and is assessed at the teaching centre and moderated by ACT — there is no external exam.

The module outcomes this unit works towards:

Learning Objective GAC017.3: Create a database with multiple tables.

Tiếng Việt

Đơn vị 3 trong số 6 đơn vị của GAC017 Computing III: Data Science and Web Apps (Level III). Mô-đun được giảng dạy trong khoảng 40 giờ học trên lớp cộng thêm 20 giờ tự học, và được đánh giá tại trung tâm giảng dạy với sự giám sát của ACT — không có kỳ thi bên ngoài.

Các kết quả học tập mà đơn vị này hướng tới:

Mục tiêu học tập GAC017.3: Tạo cơ sở dữ liệu với nhiều bảng.

Source: Cambridge International syllabus · ⁨Nguồn: Chương trình Cambridge International⁩

English
  • A relational database 关系数据库 stores data in tables 表 of rows and columns.
  • A primary key 主键 identifies a row uniquely. A foreign key 外键 points at another table's primary key, and that pointer is the relationship.
  • Normalisation 规范化 removes duplicated data so one fact lives in one place.
  • Design by asking what the entities 实体 are, then what connects them.

Worked example. A school wants to store students, courses and who takes what.

Two tables cannot do it: a student takes many courses and a course has many students. The many-to-many needs a third table — enrolments — whose rows are (student, course) pairs.

Recognising that this third table is required is the single most useful database idea in the module, and it is where most first designs go wrong.

Tiếng Việt
  • Một cơ sở dữ liệu quan hệ lưu trữ dữ liệu trong các bảng gồm hàng và cột.
  • Một khóa chính xác định duy nhất một hàng. Một khóa ngoại trỏ đến khóa chính của bảng khác, và liên kết trỏ đó chính là mối quan hệ.
  • Thiết kế bằng cách hỏi các thực thể là gì, sau đó hỏi cái gì kết nối chúng.
  • Thiết kế bằng cách hỏi các thực thể là gì, sau đó là những gì kết nối chúng.

Ví dụ minh họa. Một trường học muốn lưu trữ thông tin về học sinh, môn học và ai đang theo học môn nào.

Hai bảng không đủ: một học sinh tham gia nhiều môn học và một môn học có nhiều học sinh. Mối quan hệ nhiều-nhiều cần một bảng thứ ba — đăng ký — mà các hàng của nó là cặp (học sinh, môn học).

Nhận ra rằng bảng thứ ba này là bắt buộc là ý tưởng cơ sở dữ liệu hữu ích nhất trong mô-đun, và đây cũng là nơi phần lớn các thiết kế ban đầu mắc sai lầm.

3.4

SQL for back-end programming · ⁨SQL cho lập trình back-end⁩

Syllabus · ⁨Chương trình⁩
English

Unit 4 of 6 in GAC017 Computing III: Data Science and Web Apps (Level III). The module is taught over about 40 class hours plus 20 hours of independent study, and is assessed at the teaching centre and moderated by ACT — there is no external exam.

The module outcomes this unit works towards:

Learning Objective GAC017.4: Analyze data using SQL in order to make decisions.

Tiếng Việt

Đơn vị 4 trong số 6 đơn vị của GAC017 Computing III: Data Science and Web Apps (Level III). Mô-đun được giảng dạy trong khoảng 40 giờ học trên lớp cộng thêm 20 giờ tự học, và được đánh giá tại trung tâm giảng dạy với sự giám sát của ACT — không có kỳ thi bên ngoài.

Các kết quả học tập mà đơn vị này hướng tới:

Mục tiêu học tập GAC017.4: Phân tích dữ liệu bằng SQL để đưa ra các quyết định.

Source: Cambridge International syllabus · ⁨Nguồn: Chương trình Cambridge International⁩

English
  • SQL 结构化查询语言 asks a database questions. SELECT … FROM … WHERE … is the core.
  • JOIN 连接 combines rows from two tables on a matching key.
  • GROUP BY 分组 with COUNT, SUM or AVG answers "how many per…" questions.
  • ⚠ WHERE filters rows before grouping; HAVING filters groups after. Using the wrong one is the classic SQL error, and it usually returns a plausible wrong answer.

Worked example. Which courses have more than 20 students?

The count is a property of the group, so the filter is HAVING. Written with WHERE it does not run — and when a similar mistake does run, it silently answers a different question.

Tiếng Việt
  • SQL đặt câu hỏi cho cơ sở dữ liệu. SELECT … FROM … WHERE … là cốt lõi.
  • JOIN kết hợp các hàng từ hai bảng dựa trên khóa khớp nhau.
  • GROUP BY đi kèm với COUNT, SUM hoặc AVG để trả lời các câu hỏi "bao nhiêu mỗi…".
  • ⚠ WHERE lọc các hàng trước khi nhóm; HAVING lọc các nhóm sau. Sử dụng sai một trong hai là lỗi kinh điển trong SQL, và thường sẽ trả về một đáp án sai nhưng có vẻ hợp lý.

Ví dụ minh họa. Các khóa học nào có nhiều hơn 20 sinh viên?

SELECT c.title, COUNT(*) AS students
FROM enrolments e
JOIN courses c ON c.id = e.course_id
GROUP BY c.title
HAVING COUNT(*) > 20;

Đếm là thuộc tính của nhóm, nên bộ lọc là HAVING. Viết dưới dạng WHERE thì không được chạy — và khi một lỗi tương tự thực sự chạy, nó im lặng trả lời một câu hỏi khác.

Vocabulary · ⁨Từ vựng⁩ Train · ⁨Luyện tập⁩
English Tiếng Việt
JOIN/dʒɔɪn/ JOIN
GROUP BY/ɡruːp baɪ/ GROUP BY
parameterised query/ˌpærəˈmetəraɪzd ˈkwɪərɪ/ truy vấn tham số hóa
3.5

Connecting JavaScript with SQL · ⁨Kết nối JavaScript với SQL⁩

Syllabus · ⁨Chương trình⁩
English

Unit 5 of 6 in GAC017 Computing III: Data Science and Web Apps (Level III). The module is taught over about 40 class hours plus 20 hours of independent study, and is assessed at the teaching centre and moderated by ACT — there is no external exam.

The module outcomes this unit works towards:

Learning Objective GAC017.2: Adapt a back-end application using scripting languages to interact with databases.

Learning Objective GAC017.4: Analyze data using SQL in order to make decisions.

Tiếng Việt

Đơn vị 5 trong số 6 đơn vị của GAC017 Computing III: Data Science and Web Apps (Level III). Mô-đun được giảng dạy trong khoảng 40 giờ học trên lớp cộng thêm 20 giờ tự học, và được đánh giá tại trung tâm giảng dạy với sự giám sát của ACT — không có kỳ thi bên ngoài.

Các kết quả học tập mà đơn vị này hướng tới:

Mục tiêu học tập GAC017.2: Tùy chỉnh ứng dụng back-end sử dụng ngôn ngữ lập trình script để tương tác với cơ sở dữ liệu.

Mục tiêu học tập GAC017.4: Phân tích dữ liệu bằng SQL để đưa ra các quyết định.

Source: Cambridge International syllabus · ⁨Nguồn: Chương trình Cambridge International⁩

English
  • The back end takes a request, runs a parameterised query 参数化查询, and returns the rows as data, usually JSON 数据交换格式.
  • Parameterised means the values travel separately from the query text. That is what makes injection impossible rather than unlikely.
  • Handle the empty case. A query that returns no rows is normal, and a page that breaks on it is not finished.
Tiếng Việt
  • Phần back-end nhận yêu cầu, chạy truy vấn tham số, và trả về các hàng dưới dạng dữ liệu, thường là JSON.
  • Tham số hóa nghĩa là các giá trị di chuyển riêng biệt với văn bản truy vấn. Đó chính là điều tạo ra Bạn nghe một thay đổi về cuộc họp câu lạc bộ, giải thích một kế hoạch cho bạn bè cùng lớp, hoặc giúp một nhóm chọn phòng. Trong mỗi tình huống, tiếng Anh hữu ích sẽ kết nối thông điệp với hành động. Người nghe cần những chi tiết phù hợp. Người nói cần một điểm rõ ràng và cơ hội để kiểm tra sự hiểu biết.
  • Xử lý trường hợp trống. Một truy vấn không trả về hàng nào là bình thường, và một trang web bị lỗi do đó là Yêu cầu nhiệm vụ hiện tại của giáo viên giải thích bài đánh giá bạn cần hoàn thành. Nó có thể bao gồm bài kiểm tra nghe 听力测试, bài thuyết trình ngắn chính thức 正式演讲, thảo luận 讨论, hoặc bài tập trên lớp 平时作业. Hãy đọc yêu cầu đó để biết thời gian, tài liệu được phép, tiêu chí và quy tắc nộp bài. Hướng dẫn này không thay thế yêu cầu đó hay hứa hẹn điểm số cho một thói quen nói cụ thể.
Vocabulary · ⁨Từ vựng⁩ Train · ⁨Luyện tập⁩
English Tiếng Việt
JSON/ˈdʒeɪsn/ JSON
Data science/ˈdeɪtə ˈsaɪəns/ Khoa học dữ liệu
Descriptive statistics/dɪˈskrɪptɪv stəˈtɪstɪks/ Thống kê mô tả
visualisation/ˌvɪʒuːəlaɪˈzeɪʃn/ trực quan hóa
Correlation is not causation/ˌkɒrɪˈleɪʃn ɪz nɒt kɔːˈseɪʃn/ Tương quan không phải là nguyên nhân
3.6

Data science · ⁨Khoa học dữ liệu⁩

Syllabus · ⁨Chương trình⁩
English

Unit 6 of 6 in GAC017 Computing III: Data Science and Web Apps (Level III). The module is taught over about 40 class hours plus 20 hours of independent study, and is assessed at the teaching centre and moderated by ACT — there is no external exam.

The module outcomes this unit works towards:

Learning Objective GAC017.5: Applying Data Science to other academic areas.

Tiếng Việt

Đơn vị 6 của 6 trong GAC017 Tin học III: Khoa học dữ liệu và ứng dụng web (Cấp độ III). Mô-đun được giảng dạy trong khoảng 40 giờ học trên lớp cộng thêm 20 giờ tự học, và được đánh giá tại trung tâm giảng dạy với sự giám sát bởi ACT — không có kỳ thi ngoài.

Các kết quả học tập mà đơn vị này hướng tới:

Mục tiêu học tập GAC017.5: Áp dụng Khoa học dữ liệu vào các lĩnh vực học thuật khác.

Source: Cambridge International syllabus · ⁨Nguồn: Chương trình Cambridge International⁩

English
  • Data science 数据科学 turns data into a decision, and most of the work is before the analysis: cleaning, joining, and checking what the data can support.
  • Descriptive statistics 描述性统计 summarise; a visualisation 可视化 shows shape; neither proves a cause.
  • Correlation is not causation 相关不等于因果 — the sentence every data project needs and most omit.
  • State the limitations of your dataset. A project that names what its data cannot show scores above one that quietly overclaims.
Tiếng Việt
  • Khoa học dữ liệu biến dữ liệu thành quyết định, và phần lớn công việc diễn ra trước khi phân tích: làm sạch, gộp, và kiểm tra xem dữ liệu có thể hỗ trợ những gì.
  • Thống kê mô tả tóm tắt; biểu đồ trực quan hiển thị hình thái; cả hai đều không chứng minh được nguyên nhân.
  • Sự tương quan không phải là nguyên nhân — câu nói mà dự án dữ liệu nào cũng cần nhưng hầu hết đều bỏ qua.
  • Nêu rõ hạn chế của tập dữ liệu. Một dự án nêu rõ những gì dữ liệu không thể cho thấy sẽ được điểm cao hơn một dự án âm thầm phóng đại quá mức.
Additional notes PDF

Follow one request from browser to database

A teacher asks which clubs have places left. A spreadsheet can answer once. A web app lets a reader ask again with a different filter.

Our example has four students, four classes and five enrolments. All records are invented. It is a learning project, not a school booking service.

The three parts have different jobs:

Part Job in the example Runs where?
Browser page Collect a minimum and show a table The reader's browser
JavaScript server Check the request and run the query The local server
SQLite database Store related records and calculate course totals Inside this server process

An HTTP request 请求信息 asks for a resource. An HTTP response 响应信息 contains a status and content. The browser sends GET /api/courses?min=2. The server checks the number, then asks SQLite for course totals. It returns a JSON object 数据对象. The browser reads that object and creates table cells. The database does not send HTML to the browser. The browser does not run our server's SQL.

Start the supplied three-file example with node server.mjs. Open the address it prints. Use Node.js 22.13 or newer with the built-in SQLite module available. Keep server.mjs, index.html and courses.sql together in your own working copy. No account or package download is needed. Stop your own server with Ctrl-C.

Get the complete example files from the site's static teaching folder:

  • /static/teaching/gac_computing/database-app/server.mjs
  • /static/teaching/gac_computing/database-app/courses.sql
  • /static/teaching/gac_computing/database-app/index.html.txt
  • /static/teaching/gac_computing/database-app/README.txt

Save the first two with their shown names. Save index.html.txt as index.html. The last file has the full run and adaptation instructions. Use these paths after the site's address. The page file is supplied as text for downloading. It must run through your local example server to reach the matching API.

This example uses an in-memory database 内存数据库. Restarting creates the original records again. A file database could keep changes after restart. That needs a different storage choice.

Design relationships before writing queries

Each student has one row in students. Each class has one row in courses. An enrolment links a student to a class. A student may join several classes. A class may contain several students. This is a many-to-many relationship 多对多关系. The third table stores one student–class pair per row.

Student 1 joins courses 10 and 20. Course 10 contains students 1, 2 and 3. The same student name need not be repeated in each enrolment row. To change Mei's name, change one student record. This avoids conflicting copies.

The following two blocks form one complete script. Run them in order in a new empty practice database. Do not run it against an existing project database.

PRAGMA foreign_keys = ON;
CREATE TABLE students (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE courses (
  id INTEGER PRIMARY KEY,
  title TEXT NOT NULL,
  capacity INTEGER NOT NULL CHECK (capacity >= 0)
);
CREATE TABLE enrolments (
  student_id INTEGER NOT NULL REFERENCES students(id),
  course_id INTEGER NOT NULL REFERENCES courses(id),
  PRIMARY KEY (student_id, course_id)
);

The tables now exist. Add the fictional records, then query totals for each class.

INSERT INTO students VALUES
  (1, 'Mei'), (2, 'Kai'), (3, 'Lin'), (4, 'Jia');
INSERT INTO courses VALUES
  (10, 'Coding', 3), (20, 'Coding', 2),
  (30, 'Art', 2), (40, 'Music', 3);
INSERT INTO enrolments VALUES
  (1, 10), (2, 10), (3, 10), (1, 20), (4, 30);
SELECT c.id, c.title, c.capacity,
       COUNT(e.student_id) AS enrolled
FROM courses c
LEFT JOIN enrolments e ON c.id = e.course_id
GROUP BY c.id, c.title, c.capacity
ORDER BY enrolled DESC, c.id;

A constraint 约束 rejects data that breaks a rule. NOT NULL requires a value. CHECK (capacity >= 0) rejects negative capacity. The paired primary key rejects a repeated enrolment, such as (1,10) twice. Either ID may appear in many pairs. The pair itself must be unique.

Foreign keys reject missing students or classes when foreign-key checking is enabled. The script enables that checking explicitly. A foreign key does not create the missing row. These rules do not prevent every error. For example, capacity 3 does not itself limit enrolments to 3. A real booking operation would need a capacity check and safe handling of simultaneous bookings.

Count classes without losing empty ones

Courses 10 and 20 both have the title Coding. They are different classes. Group by the course ID as well as its title and capacity. Grouping only by title would merge their enrolments and answer the wrong question.

LEFT JOIN keeps every course, including Music with no enrolments. The unmatched course has an empty enrolment side. COUNT(e.student_id) counts matched student IDs and gives zero for Music. COUNT(*) counts the joined row, including that unmatched row, and would give Music one.

ID Course Capacity Enrolled Places left
10 Coding 3 3 0
20 Coding 2 1 1
30 Art 2 1 1
40 Music 3 0 3

The browser calculates places left as capacity minus enrolled. There are five enrolments but only four students. Mei appears in two enrolment rows. Do not label five as the number of unique students.

To keep classes with at least two enrolments, add this line after GROUP BY:

HAVING COUNT(e.student_id) >= 2

This is a query fragment, added to the complete query. It returns course 10 only. HAVING checks each group total. WHERE checks individual rows before totals are calculated. For example, WHERE c.id = 20 selects one class before grouping; it does not test its total.

Validate and bind the backend input

The route /api/courses accepts a minimum from 0 to 99. The browser number control helps users enter it. Direct requests can skip that control. The server therefore checks the input again.

It rejects negative numbers, decimals, 100, repeated minimum parameters and text. Missing min means zero. A successful query with no courses is still a valid request.

Request Status Meaning
GET /api/courses?min=2 200 One course found
GET /api/courses?min=4 200 Valid query; empty list
GET /api/courses?min=-1 400 Invalid input
GET /missing 404 Route does not exist
POST /api/courses 405 This read-only route accepts GET

A prepared statement 预编译语句 keeps the SQL structure separate from a value. The server prepares its total-by-course query with >= ?, then calls courses.all(minimum). The bound number fills the value position. It is not joined into the SQL text.

Binding values protects this query from injection through that value. It does not prove that every route or operation is secure. SQL keywords and column names cannot be supplied as ordinary bound values. Keep the query structure fixed or choose it from permitted server-owned choices.

The server sends public course totals only. Student names stay out of this response. Real records would also need access rules and permission to use them. An invented example needs no real student information.

Handle loading, empty results and failures

The browser uses fetch to request the data. It must check the response status. A completed network request may still return 400 or 500. The browser's response.ok distinguishes successful HTTP responses from those errors.

The page clears old rows before loading. Otherwise a failed request could leave old results looking current. It displays a loading message and disables the load button during the request. It then shows the result, an empty message, or a failure message. The button becomes available again so the reader can retry.

Each displayed value goes into textContent, not into HTML built from a data string. A course title becomes text inside a cell. It is not treated as page markup.

The sample uses a request number to ignore an older response after a newer request starts. This protects the page from a late response replacing the newest result. It does not change database records or make bookings safe.

Try minimum 0, 2 and 4 in that order. Expect four courses, one course and no courses. Then stop the server and try loading again. The page should explain the failure and allow a retry. Restart the server and load again. The original fictional dataset should return.

Turn results into a supported academic decision

Begin with a question: which classes currently have spare places? State your unit of analysis 分析单位: one class, identified by course ID. Check missing values, repeated enrolment pairs, valid IDs and non-negative capacities before analysis. Name the data date in a real report, because enrolments can change.

The current answer is Coding 20, Art 30 and Music 40. Music has three spare places; the other two have one each. A teacher could first check whether those places are still available before announcing them.

A bar chart could compare enrolled and capacity for each course ID. Keep the two Coding classes separate and label them with their IDs. Show zero enrolments for Music. Do not hide it because its bar is short.

Explain the limitation 局限 of this decision. These records describe four invented classes at one time. They do not measure teaching quality, future demand or why students chose a class. More enrolments do not prove that a class caused better learning. Avoid using a descriptive count as evidence for a causal claim.

A short report can use five parts: question, data and checks, method, result, limits and next action. Include the query or name the calculation so another reader can reproduce the result. Keep student and enrolment counts separate.

Practise with changes and explain your answers

  1. Sketch the three tables. Which keys link them, and why is the third table needed?
  2. Predict minimum 1 and minimum 3 before running either request.
  3. Replace COUNT(e.student_id) with COUNT(*). Which original result becomes wrong, and why?
  4. Group only by title. What happens to the two Coding classes?
  5. Add course 50, Drama, with capacity 2 and no enrolments. Predict its total and free places.
  6. Add enrolment (2,20). What should minimum 2 now return?
  7. Try duplicate pair (1,10) and missing student pair (99,10). Explain each rejection.
  8. Why must the server check a minimum that the browser already checks?
  9. Explain why an empty array gets 200, while a negative minimum gets 400.
  10. Write a two-sentence recommendation and one limitation using the original data.

Explained answers

  1. Student ID and course ID link the paired enrolment table to their parent tables. The third table represents many students in many classes without repeating names or course facts.
  2. Minimum 1 returns 10, 20 and 30. Minimum 3 returns 10 only. Both filters include equality.
  3. Music becomes one instead of zero. COUNT(*) counts the preserved unmatched course row.
  4. Coding totals combine to four. This describes a title group, not either individual class.
  5. Drama has zero enrolments and two places left. A left join keeps it at minimum 0.
  6. Coding 20 now has two enrolments. Minimum 2 returns IDs 10 and 20, with totals three and two.
  7. The paired primary key rejects the duplicate. The enabled foreign key rejects student 99, who does not exist.
  8. A caller can send a request without using the page. Browser checks cannot protect the server by themselves.
  9. No matching rows is a successful query. A negative minimum breaks the API's input rule.
  10. Check remaining places in Coding 20, Art 30 and Music 40 before offering them. Music has most spare places in this example. Invented totals cannot predict actual student demand.

Interactive lessons on this topic · ⁨Bài học tương tác về chủ đề này⁩

Work through it step by step, with instant-check exercises. · ⁨Làm theo từng bước, kèm theo bài tập kiểm tra ngay lập tức.⁩

More topics in GAC Computing · ⁨Tin học GAC⁩ · ⁨Nhiều chủ đề hơn trong GAC Computing · ⁨Tin học GAC⁩⁩

Log in or create account · ⁨Đăng nhập hoặc tạo tài khoản⁩

IGCSE, A-Level & AP