📇 記憶閃卡特訓
Ch.1 q1:
Your customer complains that he couldn't upload a 5MB profile picture to your website due to a persistent upload error. As a full-stack engineer, you immediately think of modifying a configuration file in the WAMP server. What is this configuration file called? After modifying it, what crucial steps must you take for the changes to take effect?
php.ini; Restart the server
Ch.1 q2:
Your colleague wrote a piece of PHP code to print a welcome message on a webpage, but nothing is displayed, and there are even syntax errors. Please help him find and correct two errors in this code:<?php
userName = "Alice";
echo"Welcome to the system, " + userName;
?>
The userName is not prefixed with a '$' sign;
the connector uses a '.' instead of a '+' sign.
Ch.2 q1:
You are developing a member login system. The form contains "username" and "password". In the `<form>` tag, should you choose GET or POST as the data transmission method? Please briefly explain your reasoning for choosing that method.
POST. The characteristic of POST is that it hides the parameters within the HTTP request. It is more secure than GET because the data is not displayed explicitly in the browser's address bar.
Ch.2 q2:
Your colleague is responsible for writing a photo upload function. He wrote the following HTML code, but he's complaining that the PHP backend can't retrieve the image files ($_FILES is empty). Please help him find out what key attribute is missing from the `<form>` tag?<form action="upload.php" method="post">
選擇要上傳的圖片:
<input type="file" name="avatar">
<input type="submit" value="上傳">
</form>
The `<form>` tag is missing `enctype="multipart/form-data"`.
Ch.3 q1:
Your boss wants to implement a "shopping cart" feature on their e-commerce website so that added items don't disappear when users browse different product pages. Considering security and data volume, would you choose to use cookies or sessions to store the specific list of items in the shopping cart? Why? Please explain using the concepts we just learned.
Using Session: The server will securely store the shopping cart data on the server only, and then only send the browser a 'key' to allow it to uniquely identify the session.
Ch.3 q2:
You wrote a piece of code intended to delete a cookie named "username". However, you found that the cookie still exists in your browser after execution. Please help correct this incorrect line of code so that it can actually delete the cookie:<?php
//Incorrect deletion method
setcookie("username", "");
?>
setcookie("username", "", time()-60);
Ch.4 q1:
Your colleague wrote a program to retrieve all product information. Although he successfully connected to the database and obtained `$rs`, he complained that the webpage "only ever shows the first product record; the next 99 are missing."
Based on the concepts we just learned, which PHP syntax structure (hint: a loop) is most likely to have been omitted, causing him to not retrieve all the information from the package?
use the function in a loop to iterate through all records in the result set. while($rc = mysqli_fetch_assoc($rs)) { ... }
Ch.4 q2:
When sending SQL syntax to MySQL for execution, which built-in function must be used?$rs = ____________________($conn, $sql);
mysqli_query()
Ch.5 q1:
Your webpage has a block with the id="code-box". You've requested new code data from the backend via AJAX, and the backend has returned a JSON string: '{"code": "console.log(123);", "theme": "dark"}'.
In the AJAX's success function, which built-in JavaScript method should you first use to convert this string into an object? Then, how do you update the DOM element with the id="code-box" content from the object? (Please briefly describe the steps or write the key code.)
// Assuming the received plain text string is called responseString
// Step 1: Unfreeze and convert to an object
var obj = JSON.parse(responseString);
// Step 2: Find the block and update its content
document.getElementById("code-box").innerHTML = obj.code;
Ch.5 q2:
Regarding the interaction between PHP and JSON, if we write the following code in PHP:
$data = array("name" => "Alice", "role" => "Admin");
// _______?_______
To enable the front-end AJAX to receive standard JSON data, which PHP function should be entered in the question mark above to convert and output $data?
A) json_decode($data);
B) json_encode($data);
C) JSON.stringify($data);
D) mysqli_fetch_assoc($data);
B) json_encode($data);
When the PHP backend needs to pass data to the JavaScript frontend, it must use `json_encode()` to package (freeze) the PHP array into JSON. Conversely, if PHP needs to receive JSON, it uses `json_decode()`
Ch.6 q1:
Your colleague is trying to draw a red diagonal line from the top left to the bottom right using a Canvas. He wrote the following JavaScript code. However, after execution, the Canvas on the webpage is blank. Please help him find the last crucial step he missed.var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d'); ctx.strokeStyle = 'red'; ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(200, 200);
// Which line code is missing for the lines to actually appear?
stroke()
Ch.6 q2:
When you instantiate a new `google.maps.Map` object in a webpage, in addition to specifying the HTML DOM element, you must also pass in an object containing settings. Which two properties of this setting object are mandatory to determine "where to look" and "how close to the map" at the beginning?
center, zoom
🎯 模擬測驗題庫
試卷破解與備考計畫 Sub-topic 1 (A1, A2): Q1
現在,請將自己切換到考試模式。根據今年全新的 A1/A2 題型架構,通常會給你一段未完成的 PHP 程式碼,要求你填空。請試著寫出以下 (a) 到 (d) 的正確程式碼:
————————————————————————————————————-
📝 模擬實戰題:
This is a system program used to process student course selection strings and calculate total scores.
<?php
// The system sent a string of subject names separated by commas.
$moduleStr = "ITP4523,ITP3006,ITP4688";
// (a) Please split this string of text into an array using commas "," $moduleArray
$moduleArray = ____(a)____(",", $moduleStr);
// Student's scores for each subject (associative array)
$marks = array("ITP4523"=>85, "ITP3006"=>70, "ITP4688"=>90);
$total = 0;
// (b) Please use a suitable loop to retrieve the subjects one by one from $moduleArray (name the variable $module).
____(b)____ ($moduleArray as $module) {
// (c) Extract the corresponding score from the $marks array by subject name (Key) and add it to $total.
$total += $marks[____(c)____];
}
// (d) Reassemble all subject names into a single string separated by spaces and hyphens "-" and print it out.
// Expected output: "ITP4523 - ITP3006 - ITP4688"
$finalOutput = ____(d)____(" - ", $moduleArray);
echo $finalOutput;
?>What instructions or variables should be filled in for (a), (b), (c), and (d) respectively?
(a) explode解析:我們拿到的是一長串文字 "ITP4523,ITP3006,ITP4688",目標是把它「切開」成陣列。記得壽司的比喻嗎?用刀子把長條壽司切成一塊一塊的陣列,是 explode()。
(b) foreach(c) $module解析:在 PHP 的 foreach ($moduleArray as $module) 語法中,每一次迴圈拿出來的值,會直接存放在 $module 這個變數裡。這裡沒有傳統 for 迴圈的索引值 i。而且要特別注意,PHP 的變數前面必須要有 $ 符號。(d) implode解析:我們要把陣列裡的科目,重新「串」成一個長字串。把散落的壽司塊用竹籤串起來,應該要用 implode()。
試卷破解與備考計畫 Sub-topic 1 (A1, A2): Q2
Suppose that question A1 on the exam presents the following scenario: the system generates a string of data containing a student's name and student ID, always in the format "Name: [Name], ID: [Student ID]". Using the concepts you've just learned, complete the following code to extract and print the "Student ID".
<?php
$record = "Name: Peter Parker, ID: 191234567";
// 1. Find the starting position of the three characters "ID: " followed by a space in the string.
$idLabelPos = ____(1)____($record, "ID: ");
// 2. Calculate the actual starting coordinates of the student ID (plus the length of "ID: ", which is 4).
$idStartPos = $idLabelPos + 4;
// 3. Cut out the student ID number with scissors. Since the student ID number is at the end, you don't need to provide a third parameter (length); it will cut directly to the end.
$studentID = ____(2)____($record, $idStartPos);
echo "The student ID is: " . $studentID;
?>Answer (1) & (2):
(1) strpos解析:你成功掌握了「找座標」的工具!使用 strpos() 可以精準定位出字串中特定目標(如 "ID: ")的起始索引值。
(2) substr解析:非常精準!拿到起始座標後,再加上 "ID: " 本身的長度,就會得到學號真正的開頭位置。接著用 substr() 這把剪刀,從該座標一刀剪到底(省略第三個長度參數),完美提取出學號資料。
試卷破解與備考計畫 Sub-topic 2 (A3, A4): Q1
You are writing an ordering and login system for a fast food restaurant.
<?php
// The system must start a session first
____(1)____;
// [A3 Exam Point] Check if the user has submitted a form, and the name "cannot be empty"
// Hint: Use the trap check function we just emphasized
if (____(2)____($_POST['username'])) {
echo "ERROR: Username cannot be empty!";
} else {
$user = $_POST['username'];
// [A4 Exam Point] Store this user in a cookie and set the validity period to 30 minutes
____(3)____("LoginUser", $user, time() + 30 * 60);
// [A4 Exam Point] Push the food "Burger" ordered by the user directly into the Session array named 'OrderList'
$_SESSION['OrderList']____(4)____ = "Burger";
}
?>This section of the exam will provide you with a piece of incomplete code. Please combine the logic from A3 and A4 to complete the blanks in (1) to (4).
(1): session_start()解析:這是 Session 的鐵律,要打開伺服器的專屬置物櫃,腳本最頂端一定要呼叫這個函數。
(2): empty解析:避開「幽靈包裹」陷阱。如果只用 isset(),即使使用者送出空字串,系統也會以為有資料。使用 empty() 才能精準擋下空表單。
(3): setcookie解析:題目要求「存入 (設定) Cookie」,這就像餐廳發給客人一張有期限的集點卡,必須使用 setcookie("LoginUser", $user, time() + 30 * 60)。
如果填的isset是用在客人下次來的時候,用來「檢查」他身上有沒有帶卡片 (isset($_COOKIE['LoginUser']))。
(4): []解析:PHP 最方便的陣列推入語法。不用預先設定陣列大小,直接用 [] 就能把新資料塞進 Session 裡。
試卷破解與備考計畫Sub-topic 3 (A5, B2): Q1
There is a button on the webpage. When clicked, it reads the movie.json file via AJAX and updates the movie title and poster image on the webpage.
<!-- HTML section -->
<h2 id="movieTitle">Loading...</h2>
<img id="moviePoster" src="default.png">
<script>
// JavaScript section
$.ajax({
____(1)____: 'GET', // Set request method
____(2)____: 'movie.json', // Set request path
dataType: '____(3)____', // Set data type
success: function(data) {
// 1. Update the movie title text to the <h2> tag
document.getElementById('movieTitle').innerHTML = data.title;
// 2. [B2 Must-Know Trap] Dynamically replace the path of the poster image (.png)
document.getElementById('moviePoster').____(4)____ = data.image_file;
}
});
</script>Complete the blanks in (1) to (4) below.
- (1)
type✅:精準設定 HTTP 請求方法(通常是GET或POST)。 - (2)
url✅:正確指定非同步請求要前往的目的地(例如 JSON 檔案或 PHP 腳本)。 - (3)
json✅:dataType設定為json是最關鍵的一步,這樣 jQuery 才會自動幫你把字串轉成 JavaScript Object。 - (4)
src✅:完美命中 B2 必考陷阱!要替換圖片,必須透過 DOM 操作去修改<img>標籤的src屬性。
試卷破解與備考計畫Sub-topic 4 (B1): Q1
以下程式碼改編自 2024-2025 年試卷的 Supermarket 考題。
📝 模擬實戰題:
This code retrieves all fruit products from the product table in the supermarket database and displays them on a web page table. According to the given schema, the product name field is called `prodName`, and the price field is called `price`.
<?php
// 1. Establish database connection (assuming host 127.0.0.1, username admin, password admin, database supermarket)
$conn = ____(1)____('127.0.0.1', 'admin', 'admin', 'supermarket');
$sql = "SELECT * FROM product WHERE prodCategory='fruit'";
// 2. Execute SQL query and store the results in package $rs
$rs = ____(2)____($conn, $sql);
echo '<table border="1"><tr><th>Product</th><th>Price</th></tr>';
// 3. Use loop to extract the data in the package into an "associative array"
while ($rc = ____(3)____($rs)) {
// 4. Print product name and price (Note: Please enter the array key to get the product name) printf("<tr><td>%s</td><td>$%d</td></tr>", $rc['____(4)____'], $rc['price']);
}
echo '</table>';
// 5. Release query results in memory
____(5)____($rs);
mysqli_close($conn);
?>Please provide the correct function or field name that should be filled in (1) to (5).
實戰題解答與解析
- (1)
mysqli_connect- 白話解析:這是四步舞曲的第一步「連線(Connect)」。就像是打電話給倉庫管理員,你需要提供主機位置、帳號、密碼與資料庫名稱這四個參數,才能成功建立與 MySQL 伺服器的通訊。
- (2)
mysqli_query- 白話解析:這是第二步「執行查詢(Query)」。電話打通後,你必須透過這個函數,把通訊線路(
$conn)與你的 SQL 指令($sql)交給伺服器執行,它會回傳一個裝滿資料的大包裹(Result Set)並存入$rs變數中。
- 白話解析:這是第二步「執行查詢(Query)」。電話打通後,你必須透過這個函數,把通訊線路(
- (3)
mysqli_fetch_assoc- 白話解析:這是第三步「提取資料(Fetch)」,也是最容易忘記的一步。大包裹
$rs沒辦法直接印出來,你必須用這個函數搭配while迴圈,一次拿出一個「以欄位名稱當作鑰匙的檔案夾(關聯式陣列)」。
- 白話解析:這是第三步「提取資料(Fetch)」,也是最容易忘記的一步。大包裹
- (4)
prodName- 白話解析:這是陣列取值的應用。根據題目給定的 Supermarket 綱要 (Schema),產品名稱的欄位精確名稱叫做
prodName。既然前面使用了mysqli_fetch_assoc,我們就可以直接用欄位名稱當作 Key 來取出對應的產品名稱,也就是$rc['prodName']。
- 白話解析:這是陣列取值的應用。根據題目給定的 Supermarket 綱要 (Schema),產品名稱的欄位精確名稱叫做
- (5)
mysqli_free_result- 白話解析:這是第四步「善後處理(Free)」的好習慣。把資料全部印完之後,必須使用這個函數把剛剛那個大包裹
$rs所佔用的記憶體清空,接著系統會執行下一行的mysqli_close($conn)正式把電話掛斷,結束連線。
- 白話解析:這是第四步「善後處理(Free)」的好習慣。把資料全部印完之後,必須使用這個函數把剛剛那個大包裹
試卷破解與備考計畫Sub-topic 5 (B3): Q1
這題我們直接挑戰 2024-2025 年的真實考題改編版 (Hangman 火柴人遊戲)。請將自己切換到 B3 大題的考試模式,完成以下 (1) 到 (5) 的填空:
📝 模擬實戰題:
We want to draw a stick figure on the canvas. When the user pulls the slider, the stick figure's head (circle radius) will change accordingly.
<!-- HTML section -->
<canvas id="myCanvas" width="300" height="300"></canvas>
<br>
<!-- 1. When the slider value changes, trigger the drawFigure() function to redraw the figure -->
Radius: <input type="range" id="radiusSlider" min="10" max="50" ____(1)____="drawFigure()">
<script>
function drawFigure() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Get the current value of the slider as the radius
var r = document.getElementById("radiusSlider").value;
// 2. First step: Use an eraser to clean the entire canvas (300x300)
ctx.____(2)____(0, 0, 300, 300);
// --- Draw the stick figure's head (solid circle) ---
// 3. Open the pen cap and prepare to draw a new path
ctx.____(3)____();
ctx.arc(150, 100, r, 0, 2 * Math.PI); // Draw the draft of the circle
ctx.fill(); // Fill in black
// --- Draw the stick figure's body (straight line) ---
ctx.beginPath();
ctx.moveTo(150, 100); // Move the hand to the center of the circle
// 4. With the pen tip touching the canvas, draw a straight line down to coordinates (150, 200)
ctx.____(4)____(150, 200);
// 5. After completing the draft, actually draw the line
ctx.____(5)____();
}
</script>Please tell me what instruction or attribute name should be filled in for (1), (2), (3), (4), (5) respectively?
(1) onchange
- 解析:這裡挖空的是 HTML 標籤的屬性,不是 JavaScript 繪圖指令。根據歷年試卷的設計,當滑桿或下拉選單的數值改變時("whenever the value of any input control is changed"),必須透過 HTML 的事件處理器來觸發重繪函數。正確的屬性名稱是
onchange。
(2) clearRect
- 解析:每次動態重繪前,絕對要先拿板擦把玻璃白板擦乾淨("Clears the specified rectangular area, making it fully transparent.")。
(3) beginPath
- 解析:在畫火柴人的頭(圓形
arc)之前,我們必須「打開筆蓋」宣告新路徑。對應的語法是beginPath("to begin a path")。
(4) lineTo
- 解析:要畫火柴人的身體,就是讓筆尖貼著畫布畫一條直線到指定的座標("Adds a new point and creates a line to that point...")。填空處只需要寫函數名稱
lineTo。
(5) stroke
- 解析:草稿打完後,必須呼叫這個指令,線條才會真正顯現出來("to render the current path... fill() or stroke()")。填空處填寫
stroke即可。