Creating a Search Application -
(Page 4 of 29 )
In order to connect to a database server, you need to know the hostname of the server, a username, and a password. The hostname is generally localhost because the database server normally resides on the same machine you are running your PHP code on. The following statement will make a connection to a database server.
<?php $db = mysql_connect ('localhost', 'username', 'password') or die ("Unable to connect to Database Server"); ?> |
The function mysql_connect() makes the connection to the database server and returns a resource id, which we are storing in the variable $db. The resource id is an identifier to PHP that references the database connection. This resource id can be used in other MySQL functions to differentiate between multiple database connections.
One thing you may not recognize is the use of the die function. The die function halts the execution of the script and displays the message passed to it. If we were to translate the above PHP code into English, we would say, "Make a connection to the database server 'localhost', using a username of 'username' and a password of 'password', and store an identifier for that connection in the variable $db. If you are not able to make the connection, stop executing this script and display the message 'Unable to connect to Database Server'.
Now that we have established a connection to the database server, our next task is to select the database we want to work with.
Next: >>
More Database Articles Articles
More By Matt Wade