Connecting to a MySQL database in PHP is very simple. People seem to be under the impression its very complicated.
To connect to a database firstly we need to connect to MySQL using this function: mysql_connect ( )
Here is the syntax for this:
mysql_connect('localhost', 'mysql_user', 'mysql_password')
A slightly more advanced way of doing this is using this. It makes connecting to the database a bit more smooth and should put less strain on the server.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
Now we have established a connection to MySQL we need to select a database to connect to. We do this using the mysql_select_db ( ) function.
Here is the syntax for selecting the database ($link is the MySQL connection data):
mysql_select_db('database', $link);
So its as simple as that. Here is the full code for connecting to the database:
<?php
$link
= mysql_connect(‘localhost’, ‘mysql_user’, ‘mysql_password’);
if (!$link) {
die(‘Not connected : ’ . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db(‘foo’, $link);
if (!$db_selected) {
die (‘Can\’t use foo : ’ . mysql_error());
}
?> 





































Leave a Reply