PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: Connect mysql database using php

24 Feb 2014

Connect mysql database using php

                        You must connect mysql database to insert and retrieve add from it. In php, you can connect mysql server easily. It needs only two steps.
              1. Open connection to mysql server.
              2. Select database to add and retrieve data from mysql.

Open connection to mysql:

                         You must open connection to mysql server to connect database. 


                        The mysql_connect() function is used to open connection on mysql. The syntax for open connection in mysql as follows as:


                         'localhost' is the server name.
                         root is the user name of mysql server. The 'root' is default username in mysql.
                         '' is the password of mysql server. The empty is default password in mysql.

Select database in mysql using php:

                          After opened connection to mysql database, you've to select database to add and retrieve data from it.


                          It is used to select the database in mysql server. The syntax for select database in mysql as follows:


                    'new' is the database name in mysql.

Connect mysql database in php:

                    Now combined the above two codes to one for connect mysql database using php. The php code as follows as:

   mysql_connect('localhost','root','') or die('Cannot connect mysql server');
   mysql_select_db('new') or die('cannot connect database');

                  Now you can check whether the connection is opened or not to mysql. You got error message if either mysql server is not connect or database is not selected.

Related Post: