Connecting with PHP
This guide explains how to establish a connection between a PHP application and a MySQL database using the mysqli extension. It walks through the necessary setup, configuration, and execution of a simple SQL query.
Variables
Certain parameters must be provided to establish a successful connection to a MySQL database. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:
Variable |
Description |
Purpose |
---|---|---|
USER |
MySQL username, from the Elestio service overview page |
Identifies the database user who has permission to access the MySQL database. |
PASSWORD |
MySQL password, from the Elestio service overview page |
The authentication key is required for the specified USER to access the database. |
HOST |
Hostname for MySQL connection, from the Elestio service overview page |
The address of the server hosting the MySQL database. |
PORT |
Port for MySQL connection, from the Elestio service overview page |
The network port used to connect to MySQL. The default port is 3306. |
DATABASE |
Database Name for MySQL connection, from the Elestio service overview page |
The name of the database being accessed. A MySQL instance can contain multiple databases. |
These values can usually be found in the Elestio service overview details as shown in the image below, make sure to take a copy of these details and add it to the code moving ahead.
Prerequisites
- Install PHP
- Check if PHP is installed by running:
php -v
- If not installed, download it from php.net and install.
- Make sure the mysqli extension is enabled in your php.ini configuration.
- Check if PHP is installed by running:
Code
Once all prerequisites are set up, create a new file named mysql_connect.php
and add the following code:
<?php
$host = "HOST";
$user = "USER";
$password = "PASSWORD";
$database = "DATABASE";
$port = PORT;
// Create connection
$conn = new mysqli($host, $user, $password, $database, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected to MySQL<br>";
// Run a test query to check the MySQL version
$result = $conn->query("SELECT VERSION()");
if ($result) {
$row = $result->fetch_assoc();
echo "MySQL Version: " . $row["VERSION()"];
$result->free();
} else {
echo "Query execution failed: " . $conn->error;
}
// Close connection
$conn->close();
?>
To execute the script, run the PHP server in the directory where mysql_connect.php
is located using:
php -S localhost:8000
Then, open a browser and go to:
http://localhost:8000/mysql_connect.php
If the connection is successful, the browser will display output similar to:
Connected to MySQL
MySQL Version: 8.0.36
No Comments