If you want to be considered an effective and avid PHP programmer, then there are some topics in the language that you should without a doubt know. One of the biggest, most important topics in PHP is dealing with database connections, especially ones with the MySQL database platform.
If you know how to work with a MySQL database in PHP, then you can make just about any website with dynamic content. You will be able to handle user registration, commenting, blog posts, and more. The very first thing you should learn when dealing with databases is how to connect. The following PHP code is how you connect to a MySQL database:
$host = “localhost”;
$username = “db_username”;
$password = “db_password”;
$database = “db_name”;
$dbc = mysql_connect($host, $username, $password);
mysql_select_db($db_name, $dbc);You may be sitting there wondering what this code does. If you have programmed in PHP before, then you know that $host, $username, $password, and $database are all variables. Each of these corresponds to what the variable is called. For example, $host is the host that the database is located on (99% of the time it will be localhost), $username is the username to access the database, $password is the password associated with the username, and $database is the name of the database we are connecting to.
The next two lines are PHP functions. The first function, mysql_connect, makes a connection to MySQL on your host. It returns a link identifier in case you are working with multiple connections. The parameters it takes are the database host, the username, and password. The next function, mysql_select_db, selects the database we will be using. The two parameters are the database name and the link identifier (link identifier is optional, but good practice).
Using these lines of code is how you make basic access to a database. Once you do this, you can do many things like retrieve data and add data using the mysql_query function. This function also takes in two parameters, a query string and the link identifier. A good example of using the mysql_query function is:
$query = “INSERT INTO table (column1, column2,…) VALUES (‘data1′, ‘data2′,…)”;
$result = mysql_query($query, $dbc);Obviously this code will not work with the ellipsis; this is just to show you can have as many columns in there. These two lines of code will insert data into the database. The first line assigns a query to the $query variable. The second line runs the query with the associated link identifier (optional).
Once you master these three functions, you are well on your way to becoming an expert at PHP programming with databases. There are many other functions that you should learn that work well with databases, but these 3 are a good start.