PHP Tutorial - MySQL Basic Commands

Right then, the functions I will introduce in this tutorial are mysql_connect(), mysql_select_db(), and mysql_query().

Before we start…

Most of the mysql functions can generate warnings, even if they work - you can suppress these warnings by putting an @ character before them, for example @mysql_connect(blah).

Mysql_connect()

OK then, the manual (found at php.net ) tells us that the syntax for this function is:
mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]])

erm… ok I hear you say - its alright, the manual seems to deliberately complicate things, here is how to connect to mysql in plain english:
mysql_connect(’yourhost’,'username’,'password’);
As you can see, this is somewhat easier to understand - yourhost is generally speaking, localhost, username is the username you set for mysql when you set it up, and password is the password you set for mysql when you set it up.

You can also (and I definitely recommend you do) add an ‘or die()’ command to the end of the statement, i.e.
mysql_connect(’yourhost’,'username’,'password’) or die(’Could not connect to mysql’);
This simply makes you aware of the problem when its 3am and your php script isn’t working :)

Hot Tip

When you use or die() my personal preference is to put mysql_function(blah) or die(mysql_error()); - this gives you a detailed mysql error report, which is generally more helpful than anything you could specify.

Mysql_select_db()

Again, I will state first what the manual says: (who knows, someone might decipher these definitions someday)
mysql_select_db ( string database_name [, resource link_identifier])

As the function suggests, all this function does is select a database, there is a slight difference in that this function returns a boolean (true or false) value. The *best* (i.e. the neat, consider everything) way to use this function is to specify the connection you are using, and the database you want to select, i.e.
$conn = mysql_connect($host, $user, $pass) or die(mysql_error());
$databasename = ‘databasename’;
mysql_select_db($databasename, $conn) or die(mysql_error());
This is in case you have multiple mysql connections - not a problem for most personal users, but critical in high-traffic forums for example.

Generally speaking you can get away with omitting the connection parameter, which is what I usually do (when working on personal projects), i.e.
mysql_select_db($databasename) or die(mysql_error());
where $databasename is the name of the database you wish to select for manipulation, as before Ii recommend using mysql_error() to give a better error if things should go wrong.