How to Connect To a MYSQL Database Using PHP

If you have a MySQL database to which you want to connect to, then you certainly can use a PHP program. The process may appear a bit difficult and tricky, however, you can master it by going through it once. Keep reading this article to know how you can connect to a MySQL database using PHP.

Instructions

  • 1

    First thing first, you have to note down the name, user name and password of your database. The host is usually “localhost”. Some companies like GoDaddy provide you different host name. In such a case, you will have to do a little research.

  • 2

    Now you need to create your connection file and the name of the file should be something that you can understand easily, such as connect.php or setup.php.

    In order to create a connection file, you can use any text editor like notepad. However, it is recommended that you use a PHP editing software program, as it will let you know about any error, if present in the file.

    You can use following commands to create your connection file.

    $database = "your_database";
    $username = "your_user name";
    $password = "your_password";
    $hostname = "your_host name";

  • 3

    Set your connection variables which will allow you to change anything at a later stage. After you are done with setting up your connection variables, you have to tell PHP what to do.

    You can use the function mysql_connect(), which will require you to enter the host, user name and password of your database.

    Also, you can tell it to echo if there is any error during the connection process. Following is the command that you will use here.

    mysql_connect($hostname,$username,$password) or die(mysql_error());

  • 4

    Now using the mysql_select_db() function, PHP can select your database. As the database is already connected to the host, you just have to tell the name for your database.

    Following is the command for selecting your database.

    mysql_select_db("$database") or die(mysql_error());

  • 5

    Once you are done with connecting your database with the host server and selecting it using the mysql_select_db() function, you should test if it is uploaded properly. For that purpose, you can echo or print something and check if it worked properly.

Leave a Reply

Your email address will not be published. Required fields are marked *


× 9 = thirty six