Connecting a PHP application to your database
The connection details for Traxio databases and working examples with PDO and mysqli, including safe queries and keeping credentials private.
On this page
Connection details
| Setting | Value |
|---|---|
| Host | localhost |
| Port | 3306 |
| Database | Full prefixed name, e.g. acme_shop |
| User | Full prefixed user, e.g. acme_shop |
| Charset | utf8mb4 |
PDO (recommended)
<?php
$config = require '/home/USERNAME/config/db.php';
$pdo = new PDO(
"mysql:host=localhost;dbname={$config['name']};charset=utf8mb4",
$config['user'],
$config['pass'],
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
$stmt = $pdo->prepare('SELECT id, name FROM products WHERE category = ?');
$stmt->execute([$category]);
$products = $stmt->fetchAll();mysqli
<?php
$db = new mysqli('localhost', 'acme_shop', $password, 'acme_shop');
$db->set_charset('utf8mb4');
$stmt = $db->prepare('SELECT id, name FROM products WHERE category = ?');
$stmt->bind_param('s', $category);
$stmt->execute();Always use prepared statements
Placing user input directly into SQL strings allows SQL injection, one of the most common ways sites are compromised. The ? placeholders above keep data separate from the query. Keeping your databases secure
Keep credentials out of public_html
Store the password in a file outside the web root, as in the PDO example, so a misconfiguration can never serve it as text. Storing configuration and secrets outside public_html
Remote connections
Traxio databases are intended for applications on your hosting account. Connect with localhost from your site’s code.
Prefer to follow along?
- Create a database and connect an application to it
Beginner · 15 min - Deploy a Laravel application to Traxio
Advanced · 60 min
Looking for somewhere to run PHP and MySQL? Traxio’s PHP and MySQL hosting includes phpMyAdmin.
Common questions
What is a prepared statement?
A prepared statement sends the query and the data to the database separately, so user input can never be interpreted as part of the query. It is the standard defence against SQL injection and PDO or MySQLi support it directly.
This is a general web-hosting explanation, not specific to Traxio.
Spotted something out of date or unclear? Tell us and we’ll fix it.