Store the data

The section that begins with the comment “let’s append this to a file” needs to be replaced. Here’s the old code:

//let’s append this to a file
IF ($choicefile = fopen($filename, "a")):
fwrite($choicefile, "$choice\n");
fclose($choicefile);
ELSE:
echo "<p><b>Unable to append to file choices.</b></p>\n";
ENDIF;

Also, a little above that, we store the name of the file:

$filename = "/path/to/data/choices.txt";

So, instead of setting the name of the file, we’ll need to set the name of the database and table, and the username and password we’ll use to access it. Replace the “$filename=” line with:

//table for storing data
$table = "imaginaries";

You can see that storing data in a database tends to be initially more complicated than storing it in a file. But it’s a whole lot simpler to store data in a database if, as in this case, you want to store more than one piece of information.

Replace the “let’s append this” section with:

//let’s store this in our database
$clientIP = $_SERVER['REMOTE_ADDR'];
$timestamp = time();
$insert = "INSERT INTO $table SET choice='$choice', clientIP='$clientIP', timestamp=$timestamp";
doQuery($insert);

Because we’re going to need to perform a query both for inserting and for selecting data, I’ve placed the query code into its own function:

function doQuery($query) {
$server = "localhost";
$db = "poll";
$user = "polltaker";
$pw = ".gE!KAUcuSk8";
IF (mysql_connect($server, $user, $pw)):
IF (mysql_select_db($db)):
IF (!mysql_query($query)):
mysql_problem("Unable to perform query $query");
ENDIF;
ELSE:
mysql_problem("Unable to select database $db");
ENDIF;
mysql_close();
ELSE:
mysql_problem("Unable to connect to database server $server");
ENDIF;
}

There are more places for things to go wrong here, so we have three different possible errors. Rather than duplicate the same error code each time, I’ve set the above to use a function called mysql_problem. We need to create that function:

function mysql_problem($message) {
echo "<p><b>$message: ", mysql_error(), "</b></p>\n";
}

So, instead of using “fopen” to open the file, we’re using “mysql_connect” to connect to the server and “mysql_select_db” to choose the database we’ll be storing the information in. Instead of using “fwrite” to write the data to the file, we’re using “mysql_query” to insert the data into the database. And instead of using “fclose” to close the file, we’re using “mysql_close” to close the database server connection.

Now, when you choose a favorite, the PHP script will store it in the database rather than in the file. You’ll notice that if you start testing it here, your vote counts won’t increase: that’s because the display section of our code is still looking at the file.

If you want to test at this point--and you should--you’ll need to look directly in the database using:

SELECT * FROM imaginaries;