Saving the record and checking the table
Last step: put the record into the table. The book glues the typed text straight into the SQL command. That is dangerous. Take the harmless term user’s guide: the glued command contains an apostrophe that ends the text too early, so the command breaks. And in the same way, text typed by a visitor could change what the command does. The remedy is a prepared statement. You write the command once with ? where the values go, and you send the values separately. The database treats them as plain data, so user’s guide is stored unchanged. The code below runs on an in-memory test database; for MySQL only the connection line changes. Then the page prints a message for the visitor: success, or “please fill in every field”. Finally, check that the record is really in the table by looking at the table in the database’s management page. Never assume: look.
1<?php 2$term = "user's guide"; 3echo "INSERT INTO Terms (Term) VALUES ('" . $term . "')"; 4?>
INSERT INTO Terms (Term) VALUES ('user's guide')1<?php 2$pdo = new PDO("sqlite::memory:"); 3$pdo->exec("CREATE TABLE Terms (id INTEGER PRIMARY KEY, Term TEXT, Trans TEXT, Defe TEXT, Picture TEXT)"); 4$stmt = $pdo->prepare("INSERT INTO Terms (Term, Trans, Defe, Picture) VALUES (?, ?, ?, ?)"); 5$stmt->execute(["user's guide", "دليل المستخدم", "A booklet that explains a product.", "pic/guide.webp"]); 6echo $pdo->query("SELECT Term FROM Terms")->fetchColumn(); 7?>
user's guide
1<?php 2$pdo = new PDO("mysql:host=localhost;dbname=dbdictionary;charset=utf8mb4", "dict_user", "a-long-secret"); 3?>
1<?php 2$term = "router"; 3$trans = "موجه"; 4$defe = "Passes data between networks."; 5if ($term !== '' && $trans !== '' && $defe !== '') { 6 echo "The term was saved."; 7} else { 8 echo "Please fill in every field."; 9} 10?>
The term was saved.
| id | Term | Trans | Defe | Picture |
|---|---|---|---|---|
| 1 | router | موجه | Passes data between networks. | pic/router.webp |
| 2 | cable | كابل | A wire that carries signals. | pic/cable.webp |
| 3 | browser | مستعرض | A program that shows web pages. | pic/browser.webp |
| 4 | keyboard | لوحة مفاتيح | Keys for typing letters and numbers. | pic/keyboard.webp |
On paper write the final order of the Add Term page from the top to the bottom: includes, button test, copy of the values, empty test, picture checks, prepared INSERT, message. Mark the steps that are safety checks, and write the sentence the visitor sees after a good save.