PHP has two ways of talking to the database: mysqli (MySQL and MariaDB only) and PDO (which also serves PostgreSQL and others). For a new project PDO is the safe choice. With both, the host is localhost, and the database and user names carry the account prefix.
A complete example with PDO
| 2 |
Create a file db-test.php in the site folder with this content (swap the three values for yours):<?php $dsn = 'mysql:host=localhost;dbname=account_database;charset=utf8mb4'; try { $pdo = new PDO($dsn, 'account_user', 'your-password-here', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); $row = $pdo->query('SELECT NOW() AS now_time')->fetch(PDO::FETCH_ASSOC); echo 'Connected: ' . $row['now_time']; } catch (PDOException $e) { error_log($e->getMessage()); echo 'Connection failed.'; }
|
|
| 3 |
Open db-test.php in the browser. You should see Connected and the date. If you see Connection failed, the reason is in the PHP error log. See where the error log is.
|
|
| 4 |
Delete the test file. It has done its job.
|
|
The same connection with mysqli, and a safe query
With mysqli you connect using new mysqli('localhost', 'account_user', 'password', 'account_database') and, right after, $link->set_charset('utf8mb4'). With either library, never glue variables into the SQL text: use prepared statements, where the value travels separately.
| Library |
Prepared statement |
Notes |
| PDO |
$st = $pdo->prepare('SELECT * FROM customers WHERE email = ?'); $st->execute([$email]); |
Works for MySQL, MariaDB and PostgreSQL. You change the DSN. |
| mysqli |
$st = $link->prepare('SELECT * FROM customers WHERE email = ?'); $st->bind_param('s', $email); $st->execute(); |
MySQL and MariaDB only. |
|
Three things that cause errors: using the database name without the prefix (MariaDB answers Access denied); forgetting to link the user to the database in cPanel; and writing the password into code and publishing it in a repository. Keep the details outside the code: see passwords outside the code.
|
Where to keep the connection details
In the example the values sit in the file itself, just for the test. In a real application, put them in a configuration file outside public_html (in the folder above, which the web server does not serve) and include it with require. That way, if PHP ever fails and shows the code instead of running it, the password does not leak. Note also ERRMODE_EXCEPTION: it turns an SQL error into an exception you can see, instead of a silence in which nothing happens. And open one connection per request, not one per query.
|
The example runs and your application still will not connect? Show us the exact error, without the password, and we will look.
Open a support ticket
|
RECOMMENDED PRODUCT Web hosting with cPanel Domain and SSL included, daily backups and the panel you already know. from $6.59/mo (3-year plan, with coupon) See plans |