Chapter 2. Connecting to MySQL: How it fits together

image with no caption

Knowing how things fit together before you start building is a good idea. You’ve created your first PHP script, and it’s working well. But getting your form results in an email isn’t good enough anymore. You need a way to save the results of your form, so you can keep them as long as you need them and retrieve them when you want them. A MySQL database can store your data for safe keeping. But you need to hook up your PHP script to the MySQL database to make it happen.

image with no caption

Owen’s email script was fine when he was only getting a few responses, but now he’s getting lots of emails, far more than he can manage.

He’s accidentally deleted some without reading them. And some are getting stuffed in his spam folder, which he never checks. In fact, an email he’d be very interested in seeing is hidden away in his spam folder right this moment... Owen needs a way to store all the messages so he can look at them when he has time and easily find ones related to Fang.

image with no caption

Owen really needs a way to store the alien abduction report data in a safe place other than his email Inbox. What he needs is a database, which is kinda like a fancy, ultra-organized electronic file cabinet. Since the information in a database is extremely organized, you can pull out precisely the information you need when you need it.

Databases are managed by a special program called a database server, in our case a MySQL database server. You communicate with a database server in a language it can understand, which in our case is SQL. A database server typically runs alongside a web server on the same server computer, working together in concert reading and writing data, and delivering web pages.

image with no caption

MySQL databases are organized into tables, which store information as rows and columns of related data. Most web applications use one or more tables inside a single database, sort of like different file folders within a file cabinet.

image with no caption

With alien abduction data safely stored in a MySQL database, Owen can analyze the reports from everyone who answered “yes” to the Fang question at his convenience. He just needs to use a little SQL code to talk to the database server.

So it’s decided: MySQL databases are good, and Owen needs one to store alien abduction data. He can then modify the report.php script to store data in the table instead of emailing it to himself. The table will keep the data safe and sound as it pours in from abductees, giving Owen time to sift through it and isolate potential Fang sightings. But first things first... a database!

Creating a MySQL database requires a MySQL database server and a special software tool. The reason is because, unlike a web server, a database server has to be communicated with using SQL commands.

image with no caption

Two popular MySQL tools are the MySQL terminal and phpMyAdmin. Both tools let you issue SQL commands to create databases and tables, insert data, select data, etc., but phpMyAdmin goes a step further by also providing a point-and-click web-based interface. Some web hosting companies include phpMyAdmin as part of their standard MySQL service, while the MySQL terminal can be used to access most MySQL installations.

image with no caption

You must have a MySQL database server installed before turning the page.

It’s impossible to help Owen without one! If you already have a MySQL database server installed and working, read on. If not, turn to Appendix B and follow the instructions for getting it installed. If you’re using a web hosting service that offers MySQL, go ahead and ask them to install it. Several pieces of information are required to access a MySQL database server. You’ll need them again later, so now is a good time to figure out what they are. Check off each one after you write it down.

image with no caption

With your MySQL database server information in hand, all that’s left is confirming that the server is up and running. Check one of the boxes below to confirm that you can successfully access your MySQL server.

image with no caption

Some MySQL installations already include a database. If yours doesn’t, you’ll need to create one using the CREATE DATABASE SQL command in the MySQL terminal. But first you need to open the MySQL terminal in a command-line window—just typing mysql will often work. You’ll know you’ve successfully entered the terminal when the command prompt changes to mysql>.

To create the new alien abduction database, type CREATE DATABASE aliendatabase; like this:

image with no caption

Before you can create the table inside the database, you need to make sure you’ve got our new database selected. Enter the command USE aliendatabase;

The SQL code to create a table is a little more involved since it has to spell out exactly what kind of data’s being stored. Let’s take a look at the SQL command before entering it into the terminal:

image with no caption

To actually create the new table, type the big CREATE TABLE command into the MySQL terminal. (You can find the code for the command on the web at www.headfirstlabs.com/books/hfphp.) After successfully entering this command, you’ll have a shiny new aliens_abduction table.

image with no caption

Your MySQL installation may offer the phpMyAdmin web-based tool, which lets you access your databases and tables graphically. You can use the phpMyAdmin user interface to click your way through the creation of a database and table, or enter SQL commands directly just as if you’re in the MySQL terminal. Click the SQL tab in phpMyAdmin to access a text box that acts like the MySQL terminal.

image with no caption

So the SQL tab of the phpMyAdmin application provides a way to issue SQL commands just as if you were using the MySQL terminal.

image with no caption

You use the SQL INSERT statement to insert data into a table.

The SQL language provides all kinds of cool statements for interacting with databases. One of the more commonly used statements is INSERT, which does the work of storing data in a table.

Take a look at the statement below to see how the INSERT works. Keep in mind that this statement isn’t an actual SQL statement, it’s a template of a statement to show you the general format of INSERT.

image with no caption

One of the most important things to note in this statement is that the values in the second set of parentheses have to be in the same order as the database column names. This is how the INSERT statement matches values to columns when it inserts the data.

Here’s how an INSERT statement can be used to store alien abduction data in Owen’s new aliens_abduction table.

image with no caption

Inserting data into a table is handy and all, but it’s hard not to feel a certain sense of unease at the fact that you haven’t confirmed that the data actually made its way into the table. It’s kind of like depositing money into a savings account but never being able to get a balance. The SELECT statement is how you “get the balance” of a table in a database. Or more accurately, SELECT allows you to request columns of data from a table.

image with no caption

The columns supplied to a SELECT statement must be separated by commas. Regardless of how many columns a table has, only data in the columns specified in SELECT is returned. This SELECT statement grabs all of the first and last names of alien abductees from the aliens_abduction table:

image with no caption

To check an INSERT, you need a quick way to look at all of the data in a table, not just a few columns. The SELECT statement offers a shortcut for just this thing:

image with no caption

How many rows of data does your table have in it? ______

image with no caption

It’s true, each insertion into a MySQL database requires an INSERT statement.

And this is where communicating with a MySQL database purely through SQL commands gets tedious. Sure there are lots of benefits gained by storing Owen’s data in a database, as opposed to emails in his Inbox, but managing the data manually by issuing SQL statements in a MySQL tool is not a workable solution.

The solution to Owen’s problem lies not in avoiding SQL but in automating SQL with the help of PHP. PHP makes it possible to issue SQL statements in script code that runs on the server, so you don’t need to use a MySQL tool at all. This means Owen’s HTML form can call a PHP script to handle inserting data into the database whenever it’s submitted—no emails, no SQL tools, no hassle!

image with no caption

PHP improves Owen’s alien abduction web form by letting a script send the form data directly to a database, instead of sending it to Owen’s email address and Owen entering it manually. Let’s take a closer look at exactly how the application works now that PHP is in the picture.

Before a PHP script can insert or retrieve data from a MySQL database, it must connect to the database. Connecting to a MySQL database from PHP is similar in many ways to accessing a database from a MySQL tool, and it requires the same pieces of information. Remember the three checkboxes you filled out earlier in the chapter? Here they are again, along with a new one for the name of the database—go ahead and write them down one more time.

The database server host location, username, password, and database name are all required in order to establish a connection to a MySQL database from a PHP script. Once that connection is made, the script can carry out SQL commands just as if you were entering them manually in a MySQL tool.

image with no caption

Issuing a MySQL query from PHP code first requires you to establish a connection with the database. Then you build the query as a PHP string. The query isn’t actually carried out until you pass along the query string to the database server. And finally, when you’re finished querying the database, you close the connection. All of these tasks are carried out through PHP script code. Here’s an example that inserts a new row of alien abduction data:

image with no caption

There are three main PHP functions used to communicate with a MySQL database: mysqli_connect(), mysqli_query(), and mysqli_close(). If you see a pattern it’s no accident—all of the modern PHP functions that interact with MySQL begin with mysqli_.

image with no caption

Using these three functions typically involves a predictable sequence of steps.

Let’s take a closer look at each one of these PHP database functions, starting with mysqli_connect()...

For our PHP script to be able to create a connection to the database with the mysqli_connect() function, you’ll need a few pieces of information that you’re starting to get very familiar with. Yes, it’s the same information you used earlier when working with the MySQL terminal, plus the name of the database.

image with no caption
 

Your username and password

Who

You’ll need your own username and password for your own database server. These will either be set up by you or given to you by your web hosting company when MySQL is first installed. If you set up your own MySQL, follow the instructions to give yourself a secure username and password.

 

The name of your database

What

In our example, we’ve named the database aliendatabase. Yours will be whatever name you decided to give it when you set it up earlier, or if your web hosting company created your database for you, you’ll be using that name.

 

The location of the database (a domain name, an IP address or localhost)

Where

In our example, we’re using the location of Owen’s (fictional) database. You need to use the location of your own MySQL server. Often, this is localhost if the database server is on the same machine as your web server. Your web hosting company will be able to tell you this. It may also be an IP address or a domain name like Owen’s, such as yourserver.yourisp.com.

The location, username, password, and name of the MySQL database in the mysqli_connect() function must all have quotes around them.

image with no caption

The result of calling the function is a database connection and a PHP variable that you can use to interact with the database. The variable is named $dbc in the example, but you can name it anything you like.

image with no caption

This is where the PHP die() function comes in handy.

The PHP die() function terminates a PHP script and provides feedback about code that failed. While it won’t reveal precisely what went wrong, die() tells us that something’s up and that we need to fix it. If something’s wrong with one of the four connection variables for mysqli_connect(), or if the database server can’t be located, the die() function will stop the rest of the PHP script from running and show the error message in parentheses.

image with no caption
image with no caption

Yes! Once you’ve made a database connection with mysqli_connect(), you can issue SQL queries directly from PHP.

Nearly everything you can do in the MySQL terminal you can do in PHP code with the database connection you’ve now made. It’s this connection that establishes a line of communication between a PHP script and a MySQL database. For example, now that Owen has a connection to his database, he can start inserting data into the aliens_abduction table with the mysqli_query() function and some SQL query code.

image with no caption

The mysqli_query() function needs an SQL query stored in a PHP string ($query) in order to carry out the insertion of alien abduction data.

SQL queries in PHP are represented as strings, and it’s customary to store a query in a string before passing it along to the mysqli_query() function. Since SQL queries can be fairly long, it’s often necessary to construct a query string from smaller strings that span multiple lines of code. Owen’s INSERT query is a good example of this:

image with no caption
image with no caption

With the INSERT query stored in a string, you’re ready to pass it along to the mysqli_query() function and actually carry out the insertion.

The mysqli_query() function needs two pieces of information to carry out a query: a database connection and an SQL query string.

image with no caption
image with no caption

The database connection required by the mysqli_query() function was returned to you by the mysqli_connect() function. Just in case that’s a bit fuzzy, here’s the code that established that connection:

image with no caption

So you have a database connection ($dbc) and an SQL query ($query). All that’s missing is passing them to the mysqli_query() function.

image with no caption

This code shows that calling the mysqli_query() function isn’t just a one-way communication. The function talks back to you by returning a piece of information that’s stored in the $result variable. But no actual data is returned from the INSERT query—the $result variable just stores whether or not the query issued by mysqli_query() was successful.

Since we’re only interested in executing the single INSERT query, the database interaction is over, at least as far as the script is concerned. And when you’re done with a database connection, you should close it. Database connections will close by themselves when the user navigates away from the page but, just like closing a door, it’s a good habit to close them when you’re finished. The PHP mysqli_close() function closes a MySQL database connection.

image with no caption
image with no caption

In the case of Owen’s script, we need to pass mysqli_close() the actual database connection, which is stored in the $dbc variable.

image with no caption
image with no caption

Database servers only have a certain number of connections available at a time, so they must be preserved whenever possible.

And when you close one connection, it frees that connection up so that a new one can be created. If you are on a shared database, you might only have five connections allocated to you, for example. And as you create new database-driven applications, you’ll want to keep your supply of available connections open as much as you can.

image with no caption

This is a big problem. The INSERT query needs to be inserting the form data, not static strings.

The query we’ve built consists of hard coded strings, as opposed to being driven from text data that was entered into the alien abduction form. In order for the script to work with the form, we need to feed the data from the form fields into the query string.

image with no caption

The good news is that the report.php script already has the form data stored away in variables thanks to the $_POST superglobal. Remember this PHP code?

image with no caption

So you already have the form data in hand, you just need to incorporate it into the alien abduction INSERT statement. But you need to make a small change first. Now that you’re no longer emailing the form data, you don’t need the $name variable. You do still need the first and last name of the user so that they can be added to the database—but you need the names in separate variables.

image with no caption

The new and improved report.php script is doing its job and automating the process of adding alien abduction reports to the database. Owen can just sit back and let the reports roll in... except that there’s a new problem. More data isn’t exactly making it any easier to hone in on alien abduction reports involving a potential Fang sighting.

image with no caption

Owen needs a way to find specific data, such as alien abductions where Fang was spotted.

You know what column of the database contains the information in question: fang_spotted. This column contains either yes or no depending on whether the abductee reported that they saw Fang. So what you need is a way to select only the reports in the aliens_abduction table that have a value of yes in the fang_spotted column.

You know that the following SQL query returns all of the data in the table:

SELECT * FROM aliens_abduction

The SQL SELECT statement lets you tack on a clause to control the data returned by the query. It’s called WHERE, and you tell it exactly how you want to filter the query results. In Owen’s case, this means only selecting alien abduction reports where the fang_spotted column equals yes.

image with no caption

Thanks to PHP and its functions that interface to MySQL, Owen’s MySQL database server receives the alien abduction data from an HTML form and stores it in a database table. The data waits there safely in the table until Owen gets a chance to sift through it. And when he’s ready, a simple SELECT query is all it takes to isolate abduction reports that potentially involve Fang.

image with no caption
image with no caption
image with no caption