Before you start
Create a database and a user in cPanel (see How to create a MySQL database in cPanel) and note:
- The database name and username – cPanel adds your account username as a prefix, e.g.
cpuser_shopandcpuser_shopuser - The user's password
- The host, which is localhost for scripts running on your hosting
Example using mysqli
<?php
$conn = mysqli_connect('localhost', 'cpuser_shopuser', 'your-password', 'cpuser_shop');
if (!$conn) {
die('Connection failed: ' . mysqli_connect_error());
}
echo 'Connected successfully';
mysqli_close($conn);
Example using PDO
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=cpuser_shop;charset=utf8mb4',
'cpuser_shopuser', 'your-password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected successfully';
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Common errors
- Access denied for user – the username or password is wrong, the prefix is missing, or the user hasn't been added to the database. Check MySQL Databases in cPanel.
- Unknown database – the database name is wrong or missing its prefix.
Keep credentials out of public folders where possible, and never commit them to a public code repository.