Connecting to a database from PHP
A PDO and mysqli connection example using localhost, and the most common connection errors.
Scripts running on your hosting connect to the database through the localhost host. You need the details from New MySQL database: the full database name, user and password.
PDO (recommended)#
php
<?php
$dsn = 'mysql:host=localhost;dbname=scyhost1_shop;charset=utf8mb4';
try {
$pdo = new PDO($dsn, 'scyhost1_user', 'PASSWORD', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
} catch (PDOException $e) {
error_log($e->getMessage());
exit('Database connection error.');
}mysqli#
php
<?php
$db = new mysqli('localhost', 'scyhost1_user', 'PASSWORD', 'scyhost1_shop');
if ($db->connect_error) { error_log($db->connect_error); exit('Error.'); }
$db->set_charset('utf8mb4');Most common errors#
- Access denied for user: wrong password or the user was not added to the database. Check Current Databases in MySQL Databases.
- Unknown database: the account prefix is missing from the name.
- Could not find driver: the extension is not enabled, see PHP extensions.
Errors are written to a log, see PHP errors and logs.
Vam je bil ta članek v pomoč?
Hvala za vaše mnenje! Potrebujete pomoč? Odprite zahtevek.
Sorodni članki
Creating a new MySQL databaseHow to create a database and a user in cPanel and link them with the right privileges.Remote MySQL accessHow to allow connections to your database from your computer or another server using Remote MySQL.PHP errors and logsWhere to find error_log, how to enable error logging and how to read errors when troubleshooting.phpMyAdminBrowse, edit and search database tables through a web interface.
