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.

Guide2 min readLast updated
On this page
  1. Connection details
  2. PDO (recommended)
  3. mysqli
  4. Always use prepared statements
  5. Keep credentials out of public_html
  6. Remote connections
  7. Common questions

Connection details

SettingValue
Hostlocalhost
Port3306
DatabaseFull prefixed name, e.g. acme_shop
UserFull prefixed user, e.g. acme_shop
Charsetutf8mb4
<?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?

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.

Keep going