How can you improve the code we made in the previous two stages? Here are some ideas to get you started. Search the internet if you are stuck. Then check against my solution to the extra steps (see next page).
Add comments explaining each line.
Put all the PHP code into a function with a sensible name and call it where needed.
Move the function definition above the first
html
element, but call it from the body. (use multiple PHP elements).Replace the
MessageID
comparison value in the query with a function parameter and use variable substitution to formulate the query before it is sent.Initialise
$databaseLink
outside the function and pass it to your function via a function parameter. (You will be able to reuse it across different functions before closing).Make the function return the value instead of echoing it. Then, echo the value when you call the function. (Sometimes it may be beneficial to further manipulate function outputs rather than echoing the results to the user straight away).
Add a check to see if the query caused an error or returned empty before fetching the row. Make the function return a different value in this case, like an empty string.
Specify the data types for the parameters and return value of your function in the function signature. (remember, databaseLink is a mysqli object)
Add a documentation block to your function explaining its purpose, parameters and return value.
Parent topic: Example 1
Top comments (0)