MySQL Tutorial

Part 1: Make sure PHP and MySQL is enabled

  1. Upload a page called "test.php" to your website. The page should be blank except for this text:
    <?php phpinfo(); ?>
  2. If the page shows up with your PHP version at the top and a long list of information in a purple and grey table, PHP is enabled.
    PHP Version
  3. Go to Edit > Find and enter "mysql". There should be a section titled "mysql" and it should say "MySQL Support" in the table below it. Beside that, it should say "enabled".
    MySQL Support enabled

Part 2: Creating a database

  1. Log into your cPanel (usually located at http://www.yourdomain.com/cpanel).
  2. Click on the "MySQL Databases" button.
    MySQL Databases
  3. In the "Create New Database" box, enter a name for your database and then click the "Create Database" button.
    Create New Database

Part 3: Creating a user

  1. Scroll down to "Add New User". For the username, use the database name, and then enter a password twice.
    Add New User

Part 4: Adding the user to the database

  1. Scroll down to “Add User To Database”. Select the username and database that you previously created.
    Add User To Database
  2. You will be taken to the “Manage User Privileges” page. Select the “All Privileges” checkbox and click “Make Changes”.
    Manage User Privileges

Part 5: Connect to MySQL

  1. Create a .php page and put this text into it:
    <?php

    $database = 'yourdatabase';
    $username = 'yourusername';
    $password = 'yourpassword';

    $db = new PDO('mysql:dbname=' . $database . ';host=localhost', $username, $password);

    ?>
  2. Replace "yourdatabase" with the database you created in Part 2.
  3. Replace "yourusername" with the username you entered in Part 3.
  4. Replace "yourpassword" with the password you entered in Part 3.
  5. Upload the page to your website and enter the page's URL in the address bar. If you see a blank page, you have done everything correctly. If not, you may receive an error such as:
    "Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'yourusername'@'localhost' (using password: YES) in /XXX/yourpage.php:X"
    Make sure that you have the correct database, username, and password entered. You may also need to change the host from "localhost"; try contacting your website hosting provider to determine what the host should be.
  6. Note: On every page on your website that you want to do anything to the database, you will need this code. The best thing to do is to create a page called "connect.php" or similar and place this code in it (that way, if you need to change the username/password/etc, you only have to do it once). Then add this code to the top of every page that needs to connect to the database:
    <?php include('connect.php'); ?>

    Remember to change "connect.php" to the name of your connection page.