Connecting to a Database using PHP

Selecting a reputable web hosting company is only the first step towards building and maintaining a successful website. Sometimes you may need to connect your PHP driven website to a database. For most content management systems, this is done through the config.php file. Below is a sample PHP script that connects to a database and shows all the fields for a specific table you specify in the code.

IMPORTANT: In order for the database connection to work, you will need to create the database, add the database user, and be sure that you attach a MySQL user to the database before attempting to run the script on the server.If you need to run a database script on your local computer, you will need to set up your computer to run Apache, MySQL, and PHP. You can do this by installing WAMP (Windows), MAMP (Mac), or XAMPP.

How to Connect to a Database Using PHP


//Sample Database Connection Script    
//Setup connection variables, such as database username 
//and password 

$yourfield = "your_field";   

//Connect to the database 
$connection = mysql_connect($hostname, $username, $password); mysql_select_db($dbname, $connection);   

//Setup our query 
$query = "SELECT * FROM $usertable";   

//Run the Query 
$result = mysql_query($query);   

//If the query returned results, loop through 
// each result 

    {   while($row = mysql_fetch_array($result))   
        {     $name = $row["$yourfield"];     
              echo "Name: " . $name; 
   } }   


NOTE: cPanel accounts using PHP 7 or higher would need to use mysqli instead of mysql
e.g. $connection = mysqli_connect($hostname, $username, $password);

You can find your PHP version in cPanel or a phpinfo page.

So let’s take a look at the actual code and what you need to replace:

$hostname: This almost always refers to ‘localhost’ unless you are connecting to an external database.

$username: This is the MySQL user you want to connect with. Keep in mind the user must be assigned to the database.

$password: This is the password for the username you just entered.

$dbname: This refers to the database name you wish to connect to.

$usertable: This is not needed to connect but in this script, it refers to a specific table within the database.

$yourfield: This is not needed to connect to the database but tells the script which field to echo to the screen.

With reliable PHP web hosting, you can effortlessly create and maintain dynamic websites and applications that interact with databases efficiently.


Carrie Smaha
Carrie Smaha Senior Manager Marketing Operations

Carrie enjoys working on demand generation and product marketing projects that tap into multi-touch campaign design, technical SEO, content marketing, software design, and business operations.

More Articles by Carrie

32 thoughts on “Connecting to a Database using PHP

  1. Hi,

    I’m getting the 1045 error but after following directions here, nothing helps.

    I have a subdomain set up outside my main folder on a shared server. Set the password username_databasename, connected user with DB, entered IP addresses, changed my passwords, checked my spelling, and still get 1045 error. I wasn’t sure if I should enter port 80 or 3306, so tried them both, but get the same error either way.

    Tried simply “localhost,” then “localhost/CPanelname/subdomain” with no result.


    Warning: mysqli_connect(): (HY000/1045): Access denied for user ‘username’@’localhost’ (using password: YES) in /home/clafay5/ on line 11
    Connect failed: Access denied for user ‘username’@’localhost’ (using password: YES)

    Here’s what I have in the PHP page:






        $mysqli = mysqli_connect(“localhost”, “username”, “password”, “dbName”, “80”);



    Could you please list the credentials needed to open the PHP page to SQLite so I might be sure I’m entering the correct info?

    Advice welcome and appreciated.







  2. pls help me. i dont know what is the problem to my codes. when im trying to  add a new project.its kinda work to my database. need response. 

    1. I am sorry to see that you are experiencing issues with your code. Unfortunately, without any errors to diagnose the issue, there is not much I can do to advise a solution. Is there a particular MySQL error or PHP error you are receiving?

  3. hi sir,

    my question is about ,

    i am fresher to do job .in my company they gave me task and brief explain about  database.

     INn above you mentiened core php database but u not mentioned step by step by procedure using xampp .if u keep this its get beter easy to learn from ur site .and we  cant understand the i hope that u will mention clearly.



    thanking you,



    1. Hello G.shashi,

      We do not provide support for XAMPP as it used on individual computers as opposed to hosting servers. You can find more information about XAMPP on their homepage.

      If you have any further questions or comments, please let us know.

      Arnel C.

    1. Hello Ernest,

      Thanks for the question. This is a question that often depends on preferences and development environment. However, in looking for an objective answer, I found this forum post that discusses it. Hopefully, this will help answer your question.

      If you have any further questions or comments, please let us know.

      Arnel C.

  4. Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘server39.000webh’@’localhost’ (using password: YES) in /home/a4471545/public_html/info.php on line 2

    Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /home/a4471545/public_html/info.php on line 3

    Those are the two errors messages am receiving when am trying to connect to my 000webhosting database

  5. When I add in this section:

    //Setup connection variables, such as database username
    //and password
    $yourfield = "your_field";
    //Connect to the database
    $connection = mysql_connect($hostname, $username, $password);
    mysql_select_db($dbname, $connection);

    Where do I actually replace username and password with those values? Is it just
    in the section //Connect to the database? or
    //Setup connection variables, such as database username //and password?
    or both? I'm guessing we don't want to leave them saying 'ussername' and 'password'?

    Also, setting up this connection page will ensure password and usernames won't
    show up in the source files of the code and protect the security of our website?

    Thanks for any help here!

    1. Hello Kerrie,

      Thank you for contacting us. You should replace the information within the quotation (“”) marks.

      Thank you,

  6. My Website is Not Connect with web page on Web server My website Host By So How to Connect My Website Database Pls tell Guys?

    1. Hello Mekbeb,

      Sorry for the problem with connecting your database. This will differ from host to host and may also differ based on your website’s configuration requirements. Please confer with your host to see how to connect to your database. Additionally, make sure to verify how your website is configuring it’s connection information for your website.

      If you have any further questions or comments, please let us know.

      Arnel C.

  7. Not clear about the topic above. My question is, on migrating to inmotion, what exactly do i replace “localhost” with? It’s confusing what should be used.

    1. Hello Olanrewaju,

      The problem here is that we quite often address people not being hosted with InMotion Hosting. So, if you’re not a customer and you don’t understand how to connect to your database, then you’ll need to speak with your host’s technical support, or speak with a local developer who can look at your code. For our customers, you do NOT replace “localhost” because the web server connects to the database locally in our network. The article above was created for InMotion Hosting customers in general. However, we do try to help anyone who asks, but we would need more information about how you are connecting to your database server in order to provide you an answer.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Arnel C.

  8. hi! im new to PHP but im willing to learn. we are required by oir professor to develop an “Online grading system”.. we already have our database for students’ login account (containg their username & password).. our index and login page is already okay.. but our problem is, how will I make that when a student logged in, for example me (via karen), when i logged in , my grades for the semester will appear. and when my classmate (Mark) logged in in his account, his grades na ssubjects for the semester will appear.? can you help us please?



    1. Hello Karen,

      Thank you for contacting. We are happy to help guide you, but your question will require a custom-coded solution.

      I recommend consulting a developer to assist you in working toward a solution.

      Thank you,

  9. Hello,

    I am working for a client with a VPS on inmotion. The work I’m doing is being moved from my server to the client’s. I have created the database, database user, attached the database user to the database and imported structure and data (verified using phpMyAdmin).

    However, the PHP code is unable to connect to the database. I’m using “localhost” (which is what phpMyAdmin shows), I’ve double-checked and double-set the password, ensured that username and database names are correct (including prefix with underscore). I’ve even given the database user all privileges for the purpose of troubleshooting.

    MySQL Info:

    • Server: Localhost via UNIX socket
    • Server type: MySQL
    • Server version: 5.1.73-cll – MySQL Community Server (GPLv2)
    • Protocol version: 10
    • Server charset: UTF-8 Unicode (utf8)

    PHP Version 5.4.45, using mysqli (and have verified through phpinfo() that mysqli is supported in the build).

    What assistance can you offer?




    1. Hello Keith,

      From what you told me, there shouldn’t be any issues. You may want to contact our Live Support so wec an walk through the setup step by step. It would require divulging some sensitive info you do not want to put here.

      Kindest Regards,
      Scott M

    1. Hello Michael,

      We’re not exactly sure what you’re using, or if you’re hosting a site with us. The location may differ depending on the software you’re talking about, your host, and where you have installed the website. Please provide more information about your installation – website software used, how it was installed, and where it was installed.

      If you have any further questions or comments, please let us know.

      Arnel C.

  10. hi sir. i ask if that code is the same in the storing data in the data base??? 
    and that is the code for MYSQL . how about for the sybase ?? they are the same ?? 


    1. Hello Arvin,

      Thanks for the question. I would hesitate to say it’s the same in Sybase, the underlying principles may be the same, but the code is different. We do not provide coding support as it is beyond the scope of our support.

      If you have any further questions or comments, please let us know.

      Arnel C.

  11. Hi sir i am Guna,

    I am new to PHP. i know the Concepts of Core PHP. but i have no idea about PHP mailer. concepts so please help me for that like how to send a mail using PHP. i have the files(class.pop3.php, class.phpmailer.php & class.smtp.php) but i dont know how to use that and configure. so please help me.




  12. I want to ask you, is there a standard way to connect database and correct, 

    I see a lot of connection types and display data, the standard way with php and mysql not, ?

     as I have presented is called the standard php mysql not ?

    Best Regards,

    1. Hello Viet nam,

      If you are hosting on our servers, then database is “local” to the website files, so the connection is made “locally”. Therefore, the connection setting is set to “localhost” by default. If you’re trying to connect to a database outside of the hosting server, then you would have to setup a connection string using something like the mysqli_connect() function .

      I hope that helps to answer your question. Please let us know if you need further assistance.

      Arnel C.




    connect mysql exactly

    define (“DB_HOST”, “localhost”);

    define (“DB_POST”, “”);

    define (“DB_USER”, “root”);

    define (“DB_PASSWORD”, “”);

    define (“DB_NAME”, “”);




    class Db {

          static $connection  = NULL;

    public function __constructe (){


        if (!isset(self::$connection)){

        self::$connection = mysql_connect (DB_HOST.”:” . DB_POST, DB_USER, DB_PASSWORD);

        mysql_select_db( DB_NAME , self::$connection);

        mysql_query ( ” SET CHARACTER SET utf8 “) or die (mysql_error());






    public function qurery ($query){

            $data = mysql_query($query,self::$connection);

            if (is_bool($data)) return array;

            $rows = array();

            while ($row = mysql_fetch_assoc($data)){

            $rows[] = $row;


            return $rows;










    class Result extends {

         private $_table = “name_table”;

         public function __construct(){



         public function select (){

         $query = ” SELECT * FROM ” . $this->_table;

         $select_table = $this->query($query);

         return $select_table;









         $data = new Result();

         $select = $data->select();


Was this article helpful? Join the conversation!

Shop the Black Friday Sale
Hurry! These Deals Won't Last Long