The short code and what it misses
Now we put the parts together. Remember Week 13: the form sends its values to add_term.php. The short code begins with the two includes, header and connection. Then isset($_POST['add_btn']) asks “was the Add button pressed?”, because the page also runs when it is first opened with no data. If so, the code copies the values from $_POST using the control names. A picture arrives differently: $_FILES['picture'] holds its name and a temporary place on the server, and move_uploaded_file moves it from there to the folder pic. The path of the picture is then 'pic/' joined to the name. Finally the record goes to the database; that is Lesson 3. This code works only in a perfect case. It has three weaknesses: the folder pic may not exist, empty fields would be saved as an empty record, and the visitor gets no message at all. The precise code of the next lessons fixes all three.
| What is checked | Short code | Precise code |
|---|---|---|
| the pic folder exists | no | yes |
| no field is empty | no | yes |
| the picture name is safe | no | yes |
| the record is saved safely | no | yes |
| the visitor gets a message | no | yes |
1<?php 2include("header.php"); 3include("connection.php"); 4if (isset($_POST['add_btn'])) { 5 $term = $_POST['term']; 6 $trans = $_POST['trans']; 7 $defe = $_POST['defe']; 8 $name = $_FILES['picture']['name']; 9 move_uploaded_file($_FILES['picture']['tmp_name'], 'pic/' . $name); 10 // the INSERT comes in Lesson 3 11} 12?>
1<?php 2if (!is_dir('pic')) { 3 mkdir('pic'); 4} 5?>
1<?php 2$term = ""; 3$trans = ""; 4if ($term !== '' && $trans !== '') { 5 echo "save"; 6} else { 7 echo "message: fill in all fields"; 8} 9?>
message: fill in all fields
On paper write the three weaknesses of the short code as three sentences, and next to each one the one line of PHP that fixes it (the folder test, the empty test, a message). Check that every line ends with a semicolon.