RSS

MySql Basics – Connect

Tue, Jan 19, 2010

PHP & MySql

MySql can be used to interact with databases: insert and retrieve data. It can come very handy when you need to save a collection of the same ‘kind’ ( such as products or forum messages, user accounts, etc. ) and which need to be able to be edited easily. To interact with the database you first need to connect to the host and then select the database you want to interact with. In MySql you can use the functions mysql_connect and mysql_select_db to do so.

mysql_connect("host", "username", "password");
mysql_select_db("database");

mysql_connect is used to connect to the host, which requires a username and a password. When the user for the host requires no password, you can leave out the password. The host is usually just “localhost”, depending on your host (settings). For the username you can often use “root” as default username if there aren’t any other users made for the host.

mysql_select_db is pretty much straight forward I guess. You make it select the database you’re going to use. You can also use the or die(“error message here”) to make it show an error when it fails to connect. There’s a standard mysql error message which can be called by using mysql_error() function.So it’d be:

mysql_connect("localhost", "root", "mypassword")or die(mysql_error());
mysql_select_db("mydatabase")or die(mysql_error());

So when any error occurs while connecting to the host/database, the mysql error message will appear containing the error occured.

You can also manually check whether the connection was successfully by putitng them into variables and checking the variables:

$connect = mysql_connect("localhost", "root", "mypassword");
$db      = mysql_select_db("mydatabase");

if(!$connect) {

     die("Host connection failed");

}

if(!$db) {

    die("Database connection failed");

}

?>

Now you’re ready to use the mysql functions to interact with the database, such as mysql_query, which we’ll be discussing in the next chapter.

Admin.