Before you can do anything with MySQL in PHP you must first establish a connection to your web host's MySQL database. This is done with the MySQL connect function.
If you've been around the internet a while, you'll know that IP addresses are used as identifiers for computers and web servers. In this example of a connection script, we assume that the MySQL service is running on the same machine as the script.
When the PHP script and MySQL are on the same machine, you can use localhost as the address you wish to connect to. localhost is a shortcut to just have the machine connect to itself. If your MySQL service is running at a separate location you will need to insert the IP address or URL in place of localhost. Please contact your web host for more details if localhost does not work.
<?php mysql_connect("localhost", "admin", "1admin") or die(mysql_error()); echo "Connected to MySQL<br />"; ?>
If you load the above PHP script to your webserver and everything works properly, then you should see "Connected to MySQL" displayed when you view the .php page.
The mysql_connect function takes three arguments. Server, username, and password. In our example above these arguments were:
The "or die(mysql..." code displays an error message in your browser if --you've probably guessed it -- there is an error in processing the connection! Double-check your username, password, or server if you receive this error.
After establishing a MySQL connection with the code above, you then need to choose which database you will be using with this connection. This is done with the mysql_select_db function.
<?php mysql_connect("localhost", "admin", "1admin") or die(mysql_error()); echo "Connected to MySQL<br />"; mysql_select_db("test") or die(mysql_error()); echo "Connected to Database"; ?>
So far you should have made a MySQL connection and chosen the working database. If you are up-to-date then continue the tutorial. We will be making our first table in the next lesson.
If you would rather download the PDF of this tutorial, check out our MySQL eBook from the Tizag.com store. You may also be interested in getting the PHP eBook
Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!
2003-2008 Erack Network | Copyright | Privacy Policy | Advertising Information
Site design by Seattle Web Design