Web Programming Lab 9: Databases

In this weeks lab, we finnaly moved onto the section that I have been waiting for. We finally are moving our sites to teh proper storage system of a mySQL database instead of text files for storing our users, and tracking history. To set up the connection so that it could be called on any page, I placed the connection code in my common.php file which is prepended to all other files in the directory. To set up a mySQL connection, it should look something like this:
$_GLOBALS['DB'] = mysql_connect('servername','username','password') or die('Error connecting to mysql'.mysql_error());
mysql_select_db('databasename', $_GLOBALS['DB']) or die('Error connecting to database'.mysql_error());

For using the database, query structure can look something like this to get all users:
function getAllUsers(){
$query = 'SELECT * FROM users ORDER BY username asc';
$users = array();
$result = mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
$users[] = $row;
return $users;

This example runs the query to retrieve all of the users in my users table, and then loops through, turning each returned entry into an associative array that is then appended to the users array that is returned. This is a much better storage measure than text files. Check out the site here.

  1. You left all the old text files junk in your directory…

    You could greatly reduce your smart->assign statements by leveraging associative arrays. Do a single assign and save yourself a ton of complexity.

    Code is solid, just a touch on the messy side.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: