DEV Community

David Kanekanian
David Kanekanian

Posted on • Updated on

E1 - Creating a PHP page that interacts with the database

Before starting this example, you must have completed the Create a database stage.

Create a file called index.php (see Create project folder) and follow these steps:

  1. Add an HTML html element and a body inside it.

    <html><body></body></html>
    
  2. Add a PHP element to your body.

    <?php ?>
    
  3. Connect to your database as the root user, use a query to get the message from the row just added, then close the connection.

    $databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
    $result = $databaseLink->query("SELECT Message FROM WelcomeMessage WHERE MessageID = 1;");
    
  4. Echo the data so you can see it on the HTML page, then close the database connection.

    echo $result->fetch_assoc()["Message"];
    $databaseLink->close();
    

The final code should look as follows. Test the file in your browser to get a message from the database.

<html><body><?php
$databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
$result = $databaseLink->query("SELECT Message FROM WelcomeMessage WHERE MessageID = 1;");
echo $result->fetch_assoc()["Message"];
$databaseLink->close();
?></body></html>
Enter fullscreen mode Exit fullscreen mode

Parent topic: Example 1

Top comments (0)