workshop 06 - PHP and MySQL
workshop 06 - PHP and MySQL
You will learn to connect to a MySQL database from PHP, retrieve some data, and display the data as
JSON (aka, you will write a simple REST API).
Important: there is a checkpoint at the end of each part, to ensure that you’ve done the work
correctly so far before moving on.
1. Register a MySQL account on mi-linux - Please ignore this step if you already have a MySQL
account on mi-linux.
Connect to our facilities website: https://mi-linux.wlv.ac.uk/facilities/
Choose to “register” for MySQL, read the terms and confirm.
Important: Write down/copy and paste/screenshot your credentials.
Wait for a few minutes for your account to be validated.
2. Connect to your MySQL database via a web frontend called phpMyAdmin, here:
https://mi-linux.wlv.ac.uk/phpmyadmin/
Use your credentials from step 1 above.
If you have lost or forgotten your MySQL password, you can reset it on the facilities
website (see URL in step 1)
3. Once connected, select your database on the left (you only get the one, called “db” + your
student number), then create a table called “weather” with 4 fields, as follow:
Important: always choose a suitable data type (varchar for text, int for whole numbers, float
for numbers with decimals, datetime for dates with a time etc.)
If all goes well, you should see something like this under the “Structure” tab:
4. Next week we will learn to import real data into our table from the OpenWeatherMap API,
but for now let’s just insert some dummy data. Click on the “Insert” tab, then type in some
weather data as follow and press “Go”:
5. Checkpoint: You should be able to see your data in the “Browse” tab.
1. Using Notepad++ or any text editor of your choice, create a new file called “my-api.php” or
anything similar.
Important: you can call it anything you like, but it needs to have the .php extension,
or else it won’t run. Also please get into a habit of using lowercase file names with
no spaces.
2. Type in (or copy / paste / review) the following code:
<?php
// Connect to database
$mysqli = new mysqli("localhost","your_mysql_user","your_mysql_pasword","your_database_name");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// Execute SQL query
$sql = "SELECT *
FROM weather
ORDER BY weather_when DESC limit 1";
$result = $mysqli -> query($sql);
// Error ?
if($result == false) {
echo("<h4>SQL error description: " . $mysqli -> error . "</h4>");
}
// Get data, convert to JSON and print
$row = $result -> fetch_assoc();
print json_encode($row);
// Free result set and close connection
$result -> free_result();
$mysqli -> close();
?>
3. Publish your script on mi-linux as per last week’s instructions (via SFTP) – don’t forget to set
the permissions to public.
4. Checkpoint: Browse to your file in Chrome, to make sure it works (make sure you use your
own student number and file name):
'https://mi-linux.wlv.ac.uk/~0123456/my-api.php'
It should display the data from your database table in JSON format, a bit like this:
{"weather_description":"Cloudy","weather_temperature":"12","weather_wind":"50","weather_when
":"2021-02-24 00:00:00"}
Part 3 – Modifying your client-side app
Now all we need to do is point your existing client-side JavaScript app to your newly created PHP
API, and update some of the fields in the JSON. Make a copy of your prototype1.html file called
prototype2.html, and make the following changes:
1. Update the fetch statement to point to your URL from Part 2 (make sure you use your own
student number and file name) rather than the OpenWeatherMap API:
fetch('https://mi-linux.wlv.ac.uk/~0123456/my-api.php')
2. Our JSON message is now structured differently, as per our database fields in part 2… look in
the Chrome Developer Tools:
So, update the field names in the part of the script that reads the JSON response, like this:
document.getElementById("myWeather").innerHTML =
response.weather_description;
document.getElementById("myTemperature").innerHTML =
response.weather_temperature;
(Note: the IDs of your HTML elements might be different)
Checkpoint: All done! Browse to your client app, and it should function just like before… no
change in appearance, but it’s a different story “under the hood”, as it is now fetching the
data from YOUR server-side PHP API:
It will still work if the OpenWeather API goes down (the data just won’t be as fresh).
It won’t hit the API as often, and as such won’t incur a cost.
Here is mine, as a working example (it looks very simple looks-wise!)
Part 4 – Going further (important: for fun - not required for the
assessment)
“I have finished all the work above, what shall I do next?”
1. Create more weather fields (e.g. humidity etc.) in your database table and amend PHP +
JavaScript accordingly.
2. More challenging: Currently our API always returns the same data. You could improve it by
allowing it to accept parameters (e.g., city name), and return different data depending on
the value of the parameters provided (just like the OpenWeather API).
You will need to use the $_GET array to retrieve values from the URL, and a different SQL
statement depending in the value provided.