Learn PHP – Getting dynamic (Part 2)

By   |  June 28, 2005

If you survived last month\’s ordeal (Dipping your toes in the dynamic Web), you should now consider yourself a proficient PHP installer. However, if you want to take food out of my mouth and steal my clients, you\’ll want to know how to do some real hard-core PHP coding.

The whole point of coding in PHP instead of just using HTML files is to make everything dynamic. You want the pages to make themselves, so you can spend more time counting your loot. The ideal way to get content onto your pages is from a database. First of all, databases are, as the name suggests, great places to store data. Secondly, clients pay more if you use the words \”database\” and \”dynamic\” in the quote and invoice.

Now I\’m assuming that you have some passing knowledge of databases, and have one installed on your system. I use MySQL, but PHP can also talk to PostgresSQL, Microsoft SQL and a whole host of other databases. Changing between one or the other is pretty easy once you\’ve got the basics down.
We\’ll be serving data for a simple content management system for a news site, just like www.tectonic.co.za. We\’ve got our database set up – it\’s called tectonic – and a table simply called content. In that database we\’ve got a couple of fields for our stories, such as date, headline, byline and body. There\’s also an id column with an individual identifying number for each story.

First off, we need to get our PHP program talking to the database. The primary time-waster when querying databases is waiting for the darn thing to establish a connection, so we\’ll do that right at the start and get it over with. We\’ll do this in a function so that you can type all this out once and just use it over and over, thus saving more time for sending out bills for your web development work:

function dbconnect($dbserver,$dbusername,$dbpassword,$dbname) {
$connection=mysql_connect($dbserver,$dbusername,$dbpassword) or die(mysql_error);
$db=mysql_select_db($dbname,$connection) or die(mysql_error());
}

The first line establishes the connection, and the second line selects the tectonic database. The die(mysql_error()) will display any errors and stop the program from executing further if something goes terribly, terribly wrong.
When you want to call this function, you\’d use something like this:

dbconnect(\'localhost\',\'tectonicdbuser\',\'topsecret\',\'tectonic\');

Every time you call this function you will be instantly and magically connected to your database until you either explicitly disconnect or the page finishes processing. I don\’t bother to disconnect because, well, I\’m lazy.

Right, now we want to get some info out of the database. We\’ll use the unique id number to identify which story we want, and go grab it before anyone notices.

function getstory($id) {
$sql=\"SELECT * FROM content WHERE id=$id\";
$sqlresult=mysql_query($sql) or die(mysql_error());
$result=mysql_fetch_array($sqlresult);
return($result);
}

Right, that\’s it. The first line is our SQL statement, the second line performs the query, and the third line puts the results into a variable. Finally, we return that result.

When we call the function with \”$story=getstory(\’);\”, we\’ll get all of the data in an easy-to-use associative array. If you don\’t know what an associative array is, don\’t worry, we\’ll get to that in a minute.

First let\’s see how to do a similar statement, but grab all of the stories out of the database.

function getstories() {
$result=array();
$sql=\"SELECT * FROM content\";
$sqlresult=mysql_query($sql) or die(mysql_error());
while($tmp=mysql_fetch_array($sqlresult)) {
$result[]=$tmp;
}
return($result);
}

The only two major differences between the first and second function is that we declare the $result variable upfront, and that we itterate through all the results, putting them into a two-dimensional associative array. If you still don\’t know what that means, take deep breaths and keep reading.

Now that we know how to get the data, we need to something with it. Hmm, maybe we should send it to the web page.

Now we get to the arrays. An array is like a long train, with lots of carts containing stuff trailing along. In each cart, we\’ve got some goods – in this case data. Each train cart has a number, beginning at 0. In an associative array, we give the carts names, like \”Coal Cart\” or \”Dry Goods Cart\”.

PHP has conveniently named our \”carts\” according to the fields in the contents table. In our $story variable, we\’ll get an array with names like date, headline, byline and body.

To access those \”carts\”, we use the format $story[\”date\”], $story[\”headline\”] and so forth.

PHP comes with it\’s own associative arrays, and one useful one is $_GET. This contains all of the get fields obtained from the url. So if your url is getstory.php?id=4, $_GET[\”id\”] will contain the value \”4\”.

We\’ll start our page off with some simple housework – I\’ve called my page story.php. First we\’ll get all our stories, and list the headlines with hyperlinks to display the full story.

Then we\’ll check to see if we need to display one full story, and go grab that story if that\’s the case. Otherwise we\’ll just list the first story.
Don\’t forget to include your functions in the page too – I\’m leaving them out to save space.

story.php looks like:

That wasn\’t so bad!

There are a few functions in there that may look unfamiliar to you. The first is foreach(array as item). This simply goes through each item of an array and feeds it to our script as a variable. Because our stories are an array of an array (each story is an array, and inside each story we have the data stored in an array), this function makes it really simple to still get the data out to where it needs to be.

The isset function just checked if a variable exists. If we open the page just as story.php, there will be no \”id\” get variable, so instead we just choose the id field from the first story in the database.

From here, you can start making the page look pretty with flashy lights and nifty icons. Style is something I can\’t teach you, possibly because I don\’t profess to having any. That\’s why I employ web designers. But the PHP I do myself, because I need to look like I am doing some work for my clients. Using the words \”database\” and \”dynamic\” only confuses them for a little while – they\’re more impressed with results, even if it is only 5 lines of PHP code.

Comments

One Response to “Learn PHP – Getting dynamic (Part 2)”

  1. Yves
    July 9th, 2007 @ 12:00 am

    Great article, thank you!!!You sorted some issues I was trying to learn :)

Comments are closed