How to connect to a MySQL database using PHP

How to connect to a MySQL database using PHP

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_shop and cpuser_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.

    • Related Articles

    • How to import a large MySQL database via SSH

      phpMyAdmin is fine for smaller databases, but large imports can time out. Importing over SSH is faster and more reliable. Create the database and user in cPanel (see How to create a MySQL database). Upload your .sql file to your home directory using ...
    • How to create a MySQL database in cPanel

      Most website software (WordPress, Joomla, shops) needs a database. Quickest way: MySQL Database Wizard In cPanel, open Database Wizard in the Databases section. Enter a database name and click Next Step. Create a database user with a strong password ...
    • How to check PHP settings with phpinfo

      A phpinfo page shows the PHP version and settings your site is actually using. In cPanel File Manager, open public_html (or the folder for the domain you're checking). Click + File, name it something hard to guess such as info-82731.php, and create ...
    • How to increase the PHP memory limit in WordPress

      If you see "Allowed memory size exhausted", WordPress needs more PHP memory. Step 1: Raise PHP's limit In cPanel, open MultiPHP INI Editor in the Software section. Choose your domain. Set memory_limit to 256M (or 512M for heavy sites) and click ...
    • How to transfer emails using Outlook

      If you're moving email from another provider and the old mail isn't being migrated for you, Outlook can copy it across. Step 1: Add both accounts Add your old email account and your new Managed Web mailbox to Outlook, both using IMAP. Step 2: Copy ...