
To begin working with a MySQL database in PHP, we’ll first need one. We need to create a MySQL user (with a password) and a MySQL database, then associate them with each other. Doing this is simple, but it can vary on how it is done depending on your webhost.
If your webhost runs cPanel (like BlueFur does), you’ll be able to do this all from under MySQL Databases once you have logged in. If you just have phpMyAdmin (with root privileges), you can do this under Privileges.
Once you have created your MySQL user and database (be sure to make note of the username, password and database name while creating them), we’re able to connect to MySQL within PHP. Connecting to a MySQL database using PHP is actually a two-step process. First we need to connect to the MySQL server, then we need to select the database we want to work with.
We use mysql_connect() to connect to the MySQL server, then mysql_select_db() to select the database. These functions work like this:
[code language="php"]$mysql = mysql_connect('host', 'user', 'password');
$select = mysql_select_db('database', $mysql);[/code]
The host is usually localhost, unless your MySQL server is hosted on a separate server, in which case it will be the IP address of that server. The user and password are those of the MySQL user you created earlier. The database is the name of the database you created.
There you are, connected to the MySQL server and database, and ready to manipulate it… almost. Next week we’ll be going over database structures.




