Guide Databases & MySQL

How to connect an application to MySQL

Every MySQL connection, in any language, comes down to the same four values — here is where to find them and how to use them.

Updated 8 min read Intermediate

Whatever language or framework an application is written in, connecting it to MySQL always comes down to the same four values: a host, a database name, a username and a password. Once you have those, the code that uses them is a handful of lines.

The four values, and where to find them

ValueWhere it comes from
HostAlmost always localhost when the application and database sit on the same hosting account. See why the database host is "localhost".
Database nameExactly as it appears in the databases section of your control panel, including any account prefix.
UsernameThe database user attached to that database, again exactly as shown.
PasswordSet when the user was created, and only re-readable by resetting it.

If a database and its user do not exist yet, create them first — everything below assumes both already exist and the user is attached to the database.

Connecting with PHP: mysqli

The mysqli extension is the more direct of PHP's two common ways to talk to MySQL:

<?php
$host = 'localhost';
$user = 'dbuser';
$pass = 'dbpassword';
$name = 'dbname';

$conn = mysqli_connect($host, $user, $pass, $name);

if (!$conn) {
    die('Connection failed: ' . mysqli_connect_error());
}

echo 'Connected successfully.';

Once connected, queries are run against $conn. Never build a query by pasting user input directly into the SQL string — use a prepared statement instead, which also happens to be the standard defence against SQL injection:

$stmt = mysqli_prepare($conn, 'SELECT * FROM users WHERE email = ?');
mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

Connecting with PHP: PDO

PDO is the more modern, object-oriented option, and it works the same way regardless of which database engine sits behind it:

<?php
$host = 'localhost';
$db   = 'dbname';
$user = 'dbuser';
$pass = 'dbpassword';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
    echo 'Connected successfully.';
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

Setting charset=utf8mb4 in the DSN matters — leaving it out can silently connect using an older, more limited character set even if the database itself is defined as utf8mb4. See what utf8mb4 is and why it matters if that distinction is new to you.

Keep credentials out of files that get shared or committed

Whichever method you use, avoid hardcoding real credentials in a file that might end up in version control or get copied somewhere public. An environment variable, or a configuration file kept outside the web root and excluded from git, is the safer pattern.

Connecting from outside the server

Everything above assumes the application and the database are on the same account — connecting over localhost, which never leaves the server. Connecting from somewhere else entirely — a script running on your own computer, a separate server, or a different hosting account — is a different situation:

  • The database has to accept remote connections at all. Shared hosting typically restricts MySQL to local connections only, as a security measure, since exposing it to the internet widens the attack surface considerably. A VPS or dedicated server, where you manage the database yourself, can usually be configured to allow it.
  • You need the server's actual hostname or IP, not localhost. "localhost" specifically means "this same machine" — used from anywhere else, it simply fails to resolve to the right server.
  • The connecting IP address usually needs to be allowed explicitly. Where remote access is possible, it is normally restricted to a specific list of IP addresses rather than opened to everyone, which is the correct way to do it if you do need it.

If you are not sure whether remote connections are possible on your plan, check the databases section of your control panel or contact us before assuming it is available. Building the connection logic to expect localhost and then discovering remote access is not offered on your plan is a common and avoidable source of wasted development time, so it is worth confirming this early rather than after the rest of the application is written.

When the connection fails

A failed connection almost always means one of the four values is wrong, the user is not attached to the database, or — under sustained load — the connection limit has been reached. Fixing a database connection error works through each cause in the order worth checking, and fixing a "too many connections" error covers the specific case of a database that is reachable but refusing new connections because it is already at capacity.

Related reading