Use PHP to retrieve information from a MySQL/MariaDB database
PHP is designed to easily integrate into a website. One of the most common uses for PHP is to take content from a database and output it on an HTML page. This tutorial will cover how to connect to a MySQL/MariaDB database, pull out information from a simple table, and display it in a simple HTML table.
Requirements
- A Cloud Server running Linux (any distribution)
- Apache, MySQL/MariaDB, and PHP installed and running
Apache, MySQL/MariaDB, and PHP are installed and running on a Standard Linux installation by default. If your server was created with a Minimal installation, you will need to install and configure Apache, MySQL/MariaDB, and PHP before you proceed.
Create the MySQL/MariaDB database and user
For this tutorial we will create a web page for an imaginary restaurant. The web page will display customer reviews of the restaurant.
Log in to the command line MySQL/MariaDB client:
Create a database for the reviews:
Switch to that database:
For this example, we will only create one table. It will have three fields:
- An ID field: This will be set to auto-increment.
- The reviewer's name: A text field with a 100-character limit.
- A star rating: A numeric rating of 1-5 TINYINT
- Review details: A text field with a limit of approximately 500 words. VARCHAR(4000)
Create the table:
Add two example reviews to the table:
Create a user for the database. For security reasons, it is always best to create a unique user for each database, particularly when that database will be accessed from a website.
The following command will create a user review_site with password JxSLRkdutW and grant the user access to the reviews database:
Create the PHP script
The code in this tutorial is simplified for the purpose of showing examples. When creating a website, we strongly advise you follow best security practices to ensure that your PHP scripts do not expose access to the server.
Create a file showreviews.php in your webspace and open it for editing. For example, to create the file in /var/www/html the command is:
This page will have PHP embedded inside the HTML, so the page will begin with the basic HTML declarations:
Every PHP script must begin with the PHP opening tag:
Next, add a MySQL/MariaDB connection block with the server location (localhost), the database name, and the database username and password.
Then we add a section to connect to the database, and give an error if the connection fails:
Next, add the HTML to begin the table we will use to display the data:
Follow this with the PHP code which will query the database and loop through the results, displaying each review in its own table row:
And finally, close out the table and the HTML:
To test the script, visit showreviews.php in a browser.
The full PHP script is:
- Unlimited traffic
- Fast SSD NVMe storage
- Free Plesk Web Host Edition