DEV Community

David Kanekanian
David Kanekanian

Posted on

E1 - Sample Solution

You will learn the most from this tutorial if you attempt to follow the extra steps on your own before checking this sample solution.

<?php

/**
 * Returns the welcome message associated with a message ID.
 * 
 * This message is shown to the user when they first access the index
 * page. It is meant as a welcoming message and can be personalised for
 * each user.
 *
 * When writing documentation comments, start with a single line brief
 * description, and if necessary provide additional details below.
 * You should always document each parameter and the return value of
 * a function unless it is an extremely simple function.
 *
 * @param integer $messageId ID of the message to select.
 * @param mysqli $databaseLink Connection to database to query with.
 * Must have SELECT access to the WelcomeMessage table.
 * @return string Welcome message from the database. Empty string is
 * returned if $messageId wasn't found in the database.
 */
function getWelcomeMessage(int $messageId, mysqli $databaseLink): string
{
    $result = $databaseLink->query(
        "SELECT Message FROM WelcomeMessage WHERE MessageID = $messageId;"
    );

    if (!empty($databaseLink->error) || $result->num_rows() == 0) {
        // An error occurred during the query or there were no matching records.
        // Return empty string.
        return "";
    }

    return $result->fetch_assoc()["Message"];
}
?>

<html><body><?php
// Output the message to the user as HTML output.
$databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
echo getWelcomeMessage(1, $databaseLink);
$databaseLink->close();
?></body></html>
Enter fullscreen mode Exit fullscreen mode

Parent topic: Example 1

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay