MySQL Connect
April 16, 2007
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 connection script we will 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.
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!
choose 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
Entry Filed under: mysql. .



Trackback this post | Subscribe to the comments via RSS Feed