PHP COTW: mysql_connect, mysql_select_db, mysql_query and mysql_close_db

This weeks PHP code of the week is mysql_connect, mysql_select_db and mysql_query which allow you to connect to a MySQL server, select a MySQL database and perform queries on the MySQL database.

mysql_connect allows you to connect to a local or remote MySQL server by the use of our username and password. Below is a common example of what mysql_connect could look like.

[php]$dbconnect = mysql_connect (“localhost”, “myuser”, “mypass”) or die (‘I cannot connect to the database because: ‘ . mysql_error());[/php]

The above mysql_connect uses the MySQL server ‘localhost’ with the username ‘myuser’ and the password ‘mypass’. The next part basically says if it can’t connect to the MySQL server for what ever reason it should terminate the script (‘die’) and print out some text along with the specific MySQL error returned (mysql_error).

mysql_select_db allows you to select the database on the MySQL server. If you have more than one MySQL connection, mysql_select_db has an option to allow you to choose which MySQL connection you are referring to.

[php]mysql_select_db (“mydatabase”);[/php]

To refer to a specific connection:
[php]mysql_select_db (“mydatabase”, $dbconnect2);[/php]

mysql_query enables you to perform SQL commands on the MySQL database which also allows you to perform the query on a specific MySQL connection.

[php]mysql_query(“INSERT INTO users (username, password)
VALUES (‘$form_username’,’$form_password’)”);[/php]

For specific connections do the same as in mysql_select_db:

[php]mysql_query(“INSERT INTO users (username, password)
VALUES (‘$form_username’,’$form_password’)”, $dbconnect2);[/php]

If you would like to know if your mysql_query was performed or not you can do something similar to:

[php]$sql = “INSERT INTO users (username, password)
VALUES (‘$form_username’,’$form_password’)”;

if ( !($result = mysql_query($sql)) ) {
die(‘Could not insert into users table’);

So above if it isn’t successful in the query it will terminate the script and print out the message configured. Generally you shouldn’t print out the mysql_error as you are giving away too much information, more than the average user needs to know.

mysql_close closes the MySQL connection which we have active. Usually this is not needed as all MySQL connections are closed at the end of the file


So there you have the basic functionality of connecting/disconnecting, selecting databases and querying a MySQL Server. Next week we’ll cover fetching rows, looping through rows using while, arrays and count.

Leave a Reply