# How to fetch data with PHP mysqli\_query?

With PHP, information can be easily retrieved from a MySQL or MariaDB database. A connection to the database is established, and then a SQL query is executed with PHP mysqli\_query(), allowing the results to be further processed.

## Requirements

To access data from a MySQL or MariaDB database with [PHP](https://www.ionos.co.uk/digitalguide/websites/web-development/what-is-php/), a few basic requirements must be met. First, a **working PHP environment on the server** is necessary, typically in combination with a web server such as [Apache](https://www.ionos.co.uk/digitalguide/server/know-how/what-is-apache/) or [Nginx](https://www.ionos.co.uk/digitalguide/server/configuration/nginx-basics-installation-and-set-up/). If this is not yet available, you will need to [install PHP](https://www.ionos.co.uk/digitalguide/websites/web-development/install-php/). In addition, [MySQL](https://www.ionos.co.uk/digitalguide/server/know-how/what-is-mysql/) or [MariaDB](https://www.ionos.co.uk/digitalguide/server/know-how/what-is-mariadb/) must be installed. On the PHP side, the MySQLi extension is required, though it is already included in most standard installations.

## How to retrieve information from MySQL/MariaDB with PHP step by step

In this tutorial, you’ll learn how to set up a basic MySQL/MariaDB database with a table and user, and then connect to it using PHP. Step by step, we’ll build a simple sample website that pulls restaurant reviews from the database and displays them in an [HTML table](https://www.ionos.co.uk/digitalguide/websites/web-development/html-table/).

### Step 1: Create a database

The first step is to create the database. To do this, log in to the MySQL/MariaDB client from the command line:

```none
mysql -u root -p
```

Create a database for the reviews:

```none
CREATE DATABASE reviews;
```

Switch to this database:

```none
USE reviews;
```

For this example, we will create a single table with four fields:

- ID: The primary key of the table, set to auto-increment.
- Reviewer name: A text field with a maximum length of 100 characters.
- Star rating: A numeric field (TINYINT) for values from 1 to 5.
- Review text: A text field for up to around 500 words (VARCHAR(4000)).

Create the table using the [CREATE-TABLE](https://www.ionos.co.uk/digitalguide/hosting/technical-matters/mariadb-create-table/) command:

```none
CREATE TABLE user_review (
id MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
reviewer_name VARCHAR(100),
star_rating TINYINT,
details VARCHAR(4000)
);
```

Now let’s add two sample reviews to the table:

```none
INSERT INTO user_review (reviewer_name, star_rating, details) VALUES ('Ben', '5', 'Love the calzone!');
INSERT INTO user_review (reviewer_name, star_rating, details) VALUES ('Leslie', '1', 'Calzones are the worst.');
```

### Step 2: Create a database user

In the next step, create a user for the database. For security reasons, it is recommended to set up a unique user for each database, especially if the database will be accessed from a website.

The following command creates a user named *review\_site* with the password *JxSLRkdutW* and grants access to the newly created database:

```none
CREATE USER 'review_site'@'localhost' IDENTIFIED BY 'JxSLRkdutW';
GRANT SELECT ON reviews.* TO 'review_site'@'localhost';
```

### Step 3: Create a PHP script

Note The code in this tutorial is simplified to illustrate examples. When creating a real website, it is strongly recommended to follow common security best practices to ensure that your PHP scripts do not compromise server access.

Create a file named `showreviews.php` in your webspace and open it for editing. For example, to create the file in the `/var/www/html` directory using the nano editor, run the following command:

```none
sudo nano /var/www/html/showreviews.php
```

In this example, PHP is embedded within HTML, so the page starts with the basic HTML declarations. The [CSS](https://www.ionos.co.uk/digitalguide/websites/web-design/what-is-css/) styling is also included in the HTML head:

```HTML
<!doctype html>
<html>
<head>
<meta-charset="utf-8">
<style>
    table {
        border-collapse: collapse;
        margin: 20px auto;
        width: 80%;
    }
    th, td {
        border: 1px solid black;
        padding: 5px 10px;
        text-align: left;
    }
</style>
</head>
<body>
```

Every PHP script must begin with the PHP opening tag:

```HTML
<?php
```

Next, add a MySQL/MariaDB connection block that includes the server location (`localhost`), the database name, and the database username and password.

```HTML
$hostname = "localhost";
$username = "review_site";
$password = "JxSLRkdutW";
$db = "reviews";
```

Next, add a section to establish a connection to the database. If the connection fails, an error message will appear. In both MySQL and MariaDB, you can connect your PHP script to the database using `mysqli_connect()`. This function requires the hostname, username, password, and database name, so PHP knows exactly which database to access.

```HTML
$dbconnect=mysqli_connect($hostname,$username,$password,$db);
if (!$dbconnect) {
die("Database connection failed: " . mysqli_connect_error());
}
?>
```

### Step 4: Insert the table

In the next step, add the HTML code to your script to create the table structure that will be used to display the data:

```HTML
<table>
<tr>
<td>Reviewer Name</td>
<td>Stars</td>
<td>Details</td>
</tr>
```

Next, add the PHP code that queries the database and loops through the results, displaying each review in its own table row:

```HTML
<?php
$query = mysqli_query($dbconnect, "SELECT * FROM user_review")
or die (mysqli_error($dbconnect));
while ($row = mysqli_fetch_array($query)) {
echo
"<tr>
<td>{$row['reviewer_name']}</td>
<td>{$row['star_rating']}</td>
<td>{$row['details']}</td>
</tr>\n
}
?>
```

Finally, remember to close the table and the HTML block at the end of the document:

```HTML
</table>
<div class="hash d-none" hidden>hash_fcf5f14a6fffe44125be7a5bbca552f46357b6af</div><script data-shy-copy-guard>(function(){var C=[0x00AD,0x200B,0x200C,0x200D,0x2060,0xFEFF];var s=function(t){for(var i=0;i<C.length;i++){t=t.split(String.fromCharCode(C[i])).join("");}return t;};document.addEventListener("copy",function(e){var sel=document.getSelection();if(!sel||sel.isCollapsed||!e.clipboardData){return;}e.clipboardData.setData("text/plain",s(sel.toString()));try{var d=document.createElement("div");d.appendChild(sel.getRangeAt(0).cloneContents());e.clipboardData.setData("text/html",s(d.innerHTML));}catch(x){}e.preventDefault();});})();</script></body>
</html>
```

To test the script, open `showreviews.php` in your web browser.

[![Image: Display of showreviews.php in the browser](https://www.ionos.co.uk/digitalguide/fileadmin/_processed_/6/a/csm_mysql-mariadb-php-info_cb4362a58b.webp "Display of showreviews.php in the browser")](https://www.ionos.co.uk/digitalguide/fileadmin/DigitalGuide/Screenshots_2025/mysql-mariadb-php-info.jpg) The table is now displayed in the browser. ### Step 5: Overview of the completed script

The complete PHP script is as follows:

```HTML
<!doctype html>
<html>
<head>
<meta-charset="utf-8”>
<style>
    table {
        border-collapse: collapse;
        margin: 20px auto;
        width: 80%;
    }
    th, td {
        border: 1px solid black;
        padding: 5px 10px;
        text-align: left;
    }
</style>
</head>
<body>
<?php
$hostname = "localhost";
$username = "review_site";
$password = "JxSLRkdutW";
$db = "reviews";
$dbconnect=mysqli_connect($hostname,$username,$password,$db);
if (!$dbconnect) {
die("Database connection failed: " . mysqli_connect_error());
}
?>
<table>
<tr>
<td>Reviewer Name</td>
<td>Stars</td>
<td>Details</td>
</tr>
<?php
$query = mysqli_query($dbconnect, "SELECT * FROM user_review")
or die (mysqli_error($dbconnect));
while ($row = mysqli_fetch_array($query)) {
echo
"<tr>
<td>{$row['reviewer_name']}</td>
<td>{$row['star_rating']}</td>
<td>{$row['details']}</td>
</tr>\n";
}
?>
</table>
<div class="hash d-none" hidden>hash_fcf5f14a6fffe44125be7a5bbca552f46357b6af</div><script data-shy-copy-guard>(function(){var C=[0x00AD,0x200B,0x200C,0x200D,0x2060,0xFEFF];var s=function(t){for(var i=0;i<C.length;i++){t=t.split(String.fromCharCode(C[i])).join("");}return t;};document.addEventListener("copy",function(e){var sel=document.getSelection();if(!sel||sel.isCollapsed||!e.clipboardData){return;}e.clipboardData.setData("text/plain",s(sel.toString()));try{var d=document.createElement("div");d.appendChild(sel.getRangeAt(0).cloneContents());e.clipboardData.setData("text/html",s(d.innerHTML));}catch(x){}e.preventDefault();});})();</script></body>
</html>
```


This is a markdown version of: [https://www.ionos.co.uk/digitalguide/websites/web-development/use-php-to-retrieve-information-from-a-mysql-mariadb-database/](https://www.ionos.co.uk/digitalguide/websites/web-development/use-php-to-retrieve-information-from-a-mysql-mariadb-database/) for AI/LLM consumption.