A database can be queried by using SQL which is a language to easily; add, update and select data. However SQL also allows you to alter the strucutre of a database.
The function names for other database servers are very similar except with a different first part so mysql_connect and mssql_connect for SQL Server. In order to connect to a database you first need to connect to a database, to do this you use the mysql_connect as shown below.
The variable localhost above is the server that the mysql database is located on. Localhost means that it is located on the local machine, so the same machine as the script is executing on, however this could equally be a remote server and could be indicated by the servers name or a IP address.
The variables username and password is the username and password of the mysql database server. All these details will either be initially set by you when you install MySQL or will be given to you by your web host if they you have MySQL installed. If the connection to the database wasn't successful then mysql_connect function will return a false so a faliure can be detected like so.
The die function stops execution at this point and outputs a fatal error. There would usually not be too much point in continuing execution because most scripts will be relying on the connection to the database, however this is not always the case. The mysql_error returns the last error that occured on the database as a string which provides further details as to what went wrong this function is very useful in debugging errors and should always be used when a database function fails.
The mysql_close allows you to close a connection to the database from within a script however usually this isn't neccarry as the connection will be closed anyway by PHP at the end of the script.
Again this will return false if a error occurs allowing the error to be captured as above. Otherwise the mysql_query function will return a resultset, which contains all the results of the query.
There are several options in processing this data you can return the array as a associative array with the mysql_fetch_assoc function, return it as a row with the mysql_fetch_row function or return it as a object with the mysql_fetch_object function.
All three functions to almost exactly the same task but return the data in slightly different formats as can be seen below.
As you can see with the mysql_fetch_assoc function you access the column values of the row by passing the column name present in the query as the associative array key.
When using the mysql_fetch_row function you access the column values of the row by passing the index position of the column, so the first column in the query is accessed by the index 0 and the second by the index 1 etc.
When using the mysql_fetch_object function you access the column values of the row by accessing the properties of the returned object, were each column name is a property name.