About Me

Friday, 13 April 2012

MySQL Connect

MySQL Connect

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.

MySQL localhost

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 Code:

<?php
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
echo "Connected to MySQL<br />";
?>

Display:

Connected to MySQL
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:
  • Server - localhost
  • Username - admin
  • Password - 1admin
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.

Choosing the Working Database

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 Code:

<?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";
?>

Display:

Connected to MySQL
Connected to Database

Status Check

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.

0 comments:

Post a Comment