Page 232 - Open Soource Technologies 304.indd
P. 232

Unit 14: Connecting to MySQL with PHP



            Introduction                                                                          Notes


            PHP is becoming more and more popular in web programmers, mainly because it can be
            configured to connect to various databases like Oracle, MySQL, Solid and so on. But for a MS
            SQL server, the problem is different. Though you can use PHP’s Sybase-ct support features to
            directly connect to MSSQ.

            The extension requires the MSSQL Client Tools to be installed on the system where PHP is
            installed. The Client Tools can be installed from the MSSQL Server CD or by copying ntwdblib.
            dll from\winnt\system32 on the server to\winnt\system32 on the PHP box.

            14.1  Connecting to MySQL with PHP

            14.1.1 Creating the Connection

            Opening  a  connection  to  MySQL  database  from  PHP  is  easy.  Just  use  the  mysql_connect()
            function like this
              <?php
                   $dbhost = ‘localhost’;
                   $dbuser = ‘root’;
                   $dbpass = ‘password’;

            $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die
            (‘Error connecting to mysql’);
            $dbname = ‘petstore’;
            mysql_select_db($dbname);
            ?>

            $dbhost is the name of MySQL server. When your webserver is on the same machine with
            the MySQL server you can use localhost or 127.0.0.1 as the value of $dbhost. The $dbuser and
            $dbpass are valid MySQL user name and password.

            Don’t forget to select a database using my sql_select_db() after connecting to mysql. If no database
            selected your query to select or update a table will not work.

            Sometimes a web host will require you to specify the MySQL server name and port number. For
            example if the MySQL server name is db.php-mysql-tutorial.com and the port number is 3306
            (the default port number for MySQL) then you you can modify the above code to:

              <?php
                   $dbhost = ‘db.php-mysql-tutorial.com:3306’;
                   $dbuser = ‘root’;

                   $dbpass = ‘password’;

                   $conn =  mysql_connect($dbhost, $dbuser, $dbpass) or die  (‘Error
                            connecting to mysql’);
                   $dbname = ‘petstore’;
                   mysql_select_db($dbname);

               ?>

                                             LOVELY PROFESSIONAL UNIVERSITY                                   227
   227   228   229   230   231   232   233   234   235   236   237