<?xml version="1.0" encoding="ISO-8859-1" ?>
<rss version="2.0">
<channel>
	<title>PHP Lessons</title>
	<description>Learn PHP!</description>
	<link>http://www.webdevelopforum.com/index.php</link>
	<pubDate>Wed, 08 Apr 2009 10:03:05 +0000</pubDate>
	<ttl>1</ttl>
	<item>
		<title>Lesson 8 - Homework</title>
		<link>http://www.webdevelopforum.com/topic/236-lesson-8-homework/</link>
		<description><![CDATA[Hi all,<br /><br />This week's extra work is more of a research task to look into joins on tables.  We have covered the INNER JOIN, however I recomend that you go and research about OUTER JOINS, and more about the cartesian product.<br /><br />Also, based on what was covered last night, I need you to add into the students table, 3 fields about their medical record (for example a few boolean fields about "asthma" and "currentlyinjured").  Next you need create a VIEW of those students, that could be used for admin staff to work with - thus excluding the medical information and only providing information such as name and email.  Expand on the current fields to add in data such as a phone number (will it be varchar or int?) and other "office" related information.  This is going to be our first mini project.<br /><br />Thats all - hopefully it wont take to long and as always you can email me or post below for any help or problems you might have.]]></description>
		<pubDate>Wed, 08 Apr 2009 10:03:05 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/236-lesson-8-homework/</guid>
	</item>
	<item>
		<title>Lesson 8 - Databases and SQL</title>
		<link>http://www.webdevelopforum.com/topic/235-lesson-8-databases-and-sql/</link>
		<description><![CDATA[I've restored Lesson 8 below - however I will not be writing any more lessons after this.  Please view my posts elsewhere to read why an how to contact me if you so wish.<br />
===============================================================================<br />
<br />
Hi all,<br />
<br />
Sorry I haven't posted in a few weeks - There was a bit of a mix up on what I was covering along with a few other things - but the lessons are back.<br />
<br />
This week I want to go through a bit of Database design, along with teaching some SQL (pronounced See-Qua-L ).  The first thing that you will need is to have MySQL and phpMyAdmin installed on your server...  Which (unfortunately) is beyond the scope of this tutorial... but email me if you need help because I do personally compile everythign from source on Linux Ubuntu servers anyway.  If you are using XAMPP on any system... MySQL and phpMyAdmin is already available.<br />
<br />
So access phpMyAdmin ( usually at &lt;a href="http://localhost/phpMyAdmin)" target="_blank"&gt;http://localhost/phpMyAdmin)&lt;/a&gt;.  You should see on the front page there "Create new database".  Name it something like "school".  We'll be modeling some of the database requirement's in running a  "school" system.<br />
<br />
The type of databases we are dealing with here are RDBMS or Relational DataBase Management Systems.  On a simple level its like dealing with a collection of Excel sheets ( within the one file).  Each table you store contains data - which is "related" to data in another table.  For example we will create a table to store student information, and one to store course information in, then another table to store which student's do which courses - thus creating the "relationship".<br />
<br />
The relationships are purely theoretical, they arent something we build into the database.  Systems such as phpMyAdmin and Microsoft Access can treat the relationships as something physical within the database - but it is essentially there to help us conceptualise the database, and make sure that we enter the correct information/data when performing the data entry step.<br />
<br />
So in your database, create a new table called "students".  Now here we want to have 5 fields or columns in the table.  They are as follows:<br />
<br />
&lt;u&gt;students                      &lt;/u&gt;<br />
uid       |    Integer<br />
f_name |   VarChar(20)<br />
l_name |   VarChar(20)<br />
year     |   Integer<br />
Email    |   VarChar (30)<br />
<br />
The Integer data type is similar to our integer in PHP - but its a MySQL specific one (most datbase systems such as Access Oracle and MySQL have different levels of accuracy, and not all of them support the same data types).<br />
<br />
The Varchar field is like a string, except we are specifying the number of characters that can be stored in the field.  To enter this into the phpMyAdmin "create table" form, you enter the number in backets into the "Length" field.<br />
<br />
Before you create the table, we need to do two last things...  Create a Primary key.  A Key is used to identify something  in the database, our primary key is always unique to the table.  We will create it on the uid field to create a "Unique ID".  Firstly select the "extra" dropdown and choose Auto_Incriment, and then select the primary key field.  The AutoIncr field means that the database will automatically increment the value in that field by one, for each new record in the database.<br />
<br />
Go ahead and submit it and you should be given the success page.  Now click on the "Insert" tab at the top.  This will allow us to insert data into that table.  Go ahead and enter some example data in there, 10 'students' should work nicely.<br />
<br />
Next create a "courses" table, with the following fields ( I'll let you decide on the length of the varchars).<br />
<br />
&lt;u&gt;courses&lt;/u&gt;<br />
cid              |   int<br />
name          |  varchar<br />
description   |  varchar<br />
teacher       |   int<br />
<br />
<br />
Now you can see that our course ID at the top will logically be our primary key, so go ahead and make that an auto increment and primary key.<br />
<br />
Before we enter test data here, we need to know about the teacher dont we?  There are two ways to do this.. We could use the system to store information about the teacher just as we do the students, or we could simply enter their name...  This is where you need to assess the needs of your system and database.  For this example you can do either, however I personally find its easier to place the teacher data into another table and create the relationship (which we'll do in a second).  The reason is its easier to scale, both this table and anything else that might require teacher information.  For example what happens if in a years time the school comes back to you and asks you to extend the system so that they can use it for new job placements - and not just for the student enrolment?  Also, what if a staff member gets married and changes name.... Its going to be hard to change their name in every course they teach...  not to mention time consuming and impractical!<br />
<br />
So  - whatever you decide to do, lets create another table called `enrolments`.  Notice that I'm using "`" or baticks to show the table name?  That's usually best practice, MySQL doesnt care and nor does Access - however its usually best to get your syntax correct.<br />
<br />
Our enrolments table is designed to store which student is enrolled in which course - and its where we start to get interesting relationships.  There are four types of relationships: "one to one", "one to many", "many to one", and "many to many".  A one to one relationship implies that "for this record, there is only one match in the other table".  This might be useful if you need to spread student information over multiple tables ( for example student contact information such as emergency numbers and gaurdian information, and another table for marks etc).  the one to many relationship is when one record relates to more than one in the other table, for example if you had a user table and a magazine registrations table, you would have one user to many registrations.  The many to one is the inverse of this - so the magazine registration table would have a one to many relationship, where one magazine has many subscribers.  The many to many relationship is often the hardest to understand, as many records in this database can be related to many records in the other table.  One example is if you had a table of sporting events and a table of age groups, and you wanted to generate a table of events, where every sport had an event per age group - thus many ages would have many sport's to compete in.  This by the way is called a Cartesian product (though that's just a point of interest...  where "every" record is related to "every" record).<br />
<br />
Next, you need to create an `enrolments` table.  This will store who is enrolled in what.  I personally have a unique ID as the primary key - however you dont necicarily have to for this table.  You do at least need a field to store the student ID and the course ID.<br />
<br />
So in phpMyAdmin you need to select the students table, and you will be given a list of the fileds in that table.  Below this list you should see a "relation view".  If you dont, then you may have an older version of phpMyAdmin, or you might need to enable it in the configuration file ( google is your friend).<br />
<br />
Here you can define what fields your fields link to.  You need to select your student_ID field, and do the same with the course ID....<br />
<br />
Next you need to select the field to display.  When another table links to this one - which peice of data will be displayed in PHP as the option?  Well for students we want it as the first name (or the last name... unfortunately we cannot have both)...  Do the same with the courses table and its "display name".  Now - the fun part.  Click on the database name on the left, and then click on the "designer" tab.  Have a look around in here.... this is the section of phpMyAdmin that really makes the relationships easy to understand.  You can export this to PDF along with the database layout etc - so to have a backup of the structure in hardcopy.<br />
<br />
So if you "insert" into the enrolments table, you should present you with dropdown menus for the data relationships - and it should show the name that you requested be shown.  Go ahead and enter some test data into the courses, and then enrol a few students in a few classes.... you can make sure its correct by viewing the "browse" tab for each table.<br />
<br />
Now, we get to the coding part.  For this it will all be done in the SQL tab under our database name ( so click on the database name on the left, then the SQL tab).<br />
<br />
Yhe SQL that we will use can generally be broken down into two categories, getting data and updating data.  The first is the easiest, and it works in the format of:<br />
<br />
SELECT [what] FROM [where]<br />
<br />
The [what] lists the field names that you want, and the [where] is the name or names of the tables you want to get the data from.  So lets try some:<br />
<br />
SELECT `fname`, `email` FROM `students;<br />
<br />
Enter that into the SQL and you should get all the students from the students table, however only have their firstname and their email.... yes?<br />
<br />
But I don't want everyone, I only want the people who are seniors ( or in year 10 or higher)... how do we do it?<br />
<br />
SELECT `fname`, `year`, `email` FROM `students` WHERE `year` &gt;= 10;<br />
<br />
That should work... yes?<br />
<br />
Now... joins.  I wont cover all of them here - however the concept goes:<br />
You can JOIN table together on a given reason:<br />
<br />
JOIN `table1`, `table2`<br />
ON `table1`.`field`=`table2`.`field`<br />
<br />
So we can query that:<br />
<br />
SELECT `students`.`email` , `students`.`fname`<br />
FROM `students`<br />
INNER JOIN `enrolments` ON `courseid`<br />
WHERE `enrolments`.`courseid` =1<br />
LIMIT 30<br />
<br />
Now, a few new things.  Here I'm creating an INNER JOIN on the table enrolments, where the courseid is as specified (course id1 which for me was physics).  As a result, I'm getting all my students enrolled in that course.<br />
<br />
Also  - I've added in a LIMIT statement.  What I'm doing is I'm returning the first 30 records in the query.  If there are more then they are NOT returned or displayed for me.<br />
<br />
Well thats all well and good, but what happens when a new student signs up with the system?<br />
<br />
Well:<br />
<br />
INSERT INTO [where] ([fields]) VALUES ([values list]);<br />
<br />
eg:<br />
<br />
INSERT INTO `students` (`fname`, `lname`, `email`) VALUES ('first', 'name', 'me@demo.com');<br />
<br />
Run that and look at it being added within the browse tab.  Note that the year field enters 0 instead of a Null value.  If you want the field to store a null value, then you will have to select "Not Null" when creating or editing the table structure.  Otherwise the integer field will make the value 0.  Also within the table structure you can tell it the default value if data isn't entered.... for example you could start all anonymous students in kindergarten (though you might annoy a few people).<br />
<br />
OK, so you made a mistake on your entry?  You forgot that their email is actually them@somewhere.com ?  Not a problem, we can simply UPDATE the table:<br />
<br />
UPDATE [what] SET [field]=[value] WHERE [condition];<br />
note that you usually want to set a condition because otherwise it will update ALL records in the specified table.<br />
<br />
UPDATE `students` SET `email`='them@somewhere.com' WHERE `fname`='first';<br />
<br />
One final thing to cover is creating a VIEW.  A VIEW can be considered a read only table which displays selected information.  Later on we will cover permissions on databases... but you will see that we can grant a specific user access to only a specific list of tables or views.  Say for example the students table contains a field about their medical record...  We dont want the admin to be able to view that - so we can create a view which only displays their crucial information that admin needs to know about ( so that no matter what,  the admin cannot read it)....<br />
<br />
CREATE VIEW [name] AS<br />
SELECT [what] FROM [where] WHERE [condition]<br />
<br />
This is similar to the JOIN, in fact the JOIN's can be used in here - so that a view represents data from more than one table.<br />
<br />
I personally don't use views as often as I probably should, however I do find them useful in a number of different occaisions ( such as simplifying future SQL queries whenver a specific join is constant through multiple tables).<br />
<br />
Thats all for tonight, As always post if you have questions.  Next lesson I'll cover the PHP side of handling these queries.<br />
<br />
C YA!]]></description>
		<pubDate>Tue, 07 Apr 2009 13:04:30 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/235-lesson-8-databases-and-sql/</guid>
	</item>
	<item>
		<title>Lesson 7 - Object Oriented (2)</title>
		<link>http://www.webdevelopforum.com/topic/212-lesson-7-object-oriented-2/</link>
		<description><![CDATA[I've restored Lesson 7 below - but there will be no more lessons after I've restored 7 and 8.  Please view my posts elsewhere for the discussion on why - and how to contact me if you so wish.<br />
<br />
===============================================================================<br />
<br />
Welcome again.<br />
<br />
Well straight into it.  Overloading is the idea of having functions do the same thing, with different numbers of arguments.  In compiled languages such as C++ you usually have to define multiple functions with different arguments.  In PHP we dont have to do this (in fact we cant do this), so instead we tell the function a default value for arguments:<br />
<br />
function display ($fname="default", $lname="surname") {}<br />
<br />
so we can call it like:<br />
<br />
display("ME");<br />
<br />
This way - we can "overload" our functions, allowing us to have different "setters" without having to manaully set() each variable. <br />
<br />
This brings me to another point about class design.  Most of the time you want to have the member variables private, and only allow access to them through methods of the class.  Often you call these "getters" and "setters":<br />
<br />
class name {<br />
  private $variable;<br />
  public function setvar($val) {}<br />
  public function getvar() {return $this-&gt;variable; }<br />
}<br />
<br />
Now clearly you can see that its a basic example - but it allows your to really secure your classes.<br />
<br />
<br />
Inheritence allows you to "inherit" parts of a parent class:<br />
<br />
class classone {<br />
 .... stuff<br />
}<br />
<br />
class childclass extends classone {<br />
  parent::function();<br />
}<br />
<br />
<br />
So here I've declared the parent class, and then I've inherited its properties in the child class.  Also in the child class I've called the function called function - but the one that belongs to the parent class - so that if you decide to override the child class method then you can still access the parent member.  A child class inherits public and protected members from the parent, however private members are NOT inherited into the child.  Generally, if you are designing a class for inheritence... protected is the "family friendly" private scope.<br />
<br />
This technique becomes very useful when modeling things with similar properties.  For example imagine a network.  You could have a parent class Node, which contains an IP address.  Then child classes could be DNSServer, Router etc. - all of which would have an IP address, but would have other properties as well.<br />
<br />
As you can see, these techniques can become very powerful.  Over all - its called polymorphism...  By being about to access parents and change the way we call different objects, our code becomes much more powerful.<br />
<br />
<br />
So to wrap up this lesson, I'll leave you with a few examples (Which will probably extend into homework)...<br />
   - Modeling an HTML form, each child class extending a parent "Element" class.<br />
   - Creating a game, where each character or object on screne inherits from a parent - containing animation functions etc.<br />
   - Easily accessing file access methods, and wrappers that are object oriented for basic I/O operations.<br />
<br />
So hopefully this hasn't been too much to take in at once.  For homework I'll be setting a few modelling things with OOP - things like the HTML form.  As such it wont be code at all - but as more of a theory exercise, planning out all of the work.<br />
<br />
Soon(ish), once weve had a chance to actually build something usable, I'll talk more about "projects" and "styles" of coding etc. - which I personally find just as important as teh code itself.  I Often find myself planning a few hours coding for more hours than it takes me to code - as I work through examples of test data, makeing sure that the theory and model behind it makes it fit the requirements and is easy to debug - but more on that when it comes.<br />
<br />
C ya!]]></description>
		<pubDate>Mon, 16 Mar 2009 12:11:11 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/212-lesson-7-object-oriented-2/</guid>
	</item>
	<item>
		<title>Lesson 6 - Object Oriented (1)</title>
		<link>http://www.webdevelopforum.com/topic/204-lesson-6-object-oriented-1/</link>
		<description><![CDATA[Hi,<br />
<br />
This week I'm covering Object Oriented Programming.  Note that this is an entirely seperate "type" altogether (one I may add that I love).  We havent really done any large applications/scripts - but with OOP you'll start to see how useful it can be when we start on our main project.<br />
<br />
Up until now we've been using Integers, or strings; essentially single data types ( or basic data types).  We can create our own data types by using Classes.  These are sort of like compound types...<br />
<br />
<pre class='prettyprint'>class Car {
    $speed;
    $direction; // 0-360 degrees
    function increaseSpeed() { $this-&gt;speed += 10; }
    function turnRight() { $this-&gt;direction += 90; }
}</pre><br />
<br />
This gives is a good starting point for classes.  Firstly, we create a new "Instance" of this class/object by using the new operator:<br />
<br />
<pre class='prettyprint'>$myHonda = new Car();

so now I can go:
$myHonda-&gt;speed = 40;
$myHonda-&gt;turnRight();
echo "My Speed: ".$myHonda-&gt;speed."&#092;n";</pre><br />
<br />
As you can see, my compound data type called "Car" makes it much easier to "organise" my code.  So if I wanted 2 cars, I could simply create two instances of the object.<br />
<br />
So, cant I acheive all of the above using an array of data?  Sure:<br />
<br />
<pre class='prettyprint'>$car = Array("speed"=&gt;40, "direction"=&gt;90);
$car&#91;'speed'&#93; += 60; // Accelerate 60 km/h</pre><br />
<br />
however - its not as nice... Try finding a nice and easy way to create a new car...  without having to know all about its structure.  After all - we dont build a car (like the array example) we buy them (ie, premade as in the class example).<br />
<br />
So, what about if we tried to build a BankAccount? Well firstly, we don't want anyone to be able to modify our account balance, or password do we.  So we make those member variables private, and only allow people to use the functions:<br />
<br />
<pre class='prettyprint'>class BankAccount {
    private $balance;
    private $password;
    public function __construct($pass) {
        $this-&gt;password=$pass;
        $this-&gt;balance = 10.00;
    }
    public function addFunds($howMuch) {
        if($howMuch &gt; 0) {
            $this-&gt;balance += $howMuch;
        }
    }
    public function checkPassword($pass) {
        if($this-&gt;password == $pass) {
            return True;
        }
        else {
            return False;
        }
    }
}</pre><br />
<br />
Ok.  So the above examples dont cover all the needed functions.... clearly we aren't able to reset a password, or withdraw from the account... but you can see that by protecting our "Member variables", we can use functions to ensure that we can control what's happening to our function. By using the keyword private or public we are declaring the scope in which they are available in.  Public means that everyone can access it.  Protected means that only itself and child classes can access it  (see inheritence below), and private means that only the current class can access it.<br />
<br />
So far we've had fairly simple classes that only use basic data types.  But we can have classes who's member variables are other objects.  We are ( to a certain extent) extending the data you can use in PHP.  For example (this will be homework), we can build a Bank class, which has an array of Employee's, and an array of BankAccounts (similar to what we built above).<br />
<br />
Some real applications of classes and OOP is building a website or system that can easily be extended ( for example Joomla!, a PHP based CMS which easily allows you to add templates, different components (create and modify content) and even language packs.  You create a basic class design ( a list of functions that the class must use) and then it doesnt matter what the class is, you create a new instance of it and call the functions.  Here is a rough idea ( this isnt full code, I havent defined all of the different classes).<br />
<br />
<pre class='prettyprint'>$pluginName = "ForumClass";

$pageClass = new $PluginName();
$pageClass-&gt;parseData($db);
$pageClass-&gt;displayOnPage();</pre><br />
<br />
<br />
Here, we are creating a new "ForumClass" even though we dont know that.  in this way, we can send the class/plugin name through a form etc.<br />
<br />
Ok, so how does someone know how to create a plugin for your system, and how do you enforce your functions on their plugin? Interfaces:<br />
<br />
<pre class='prettyprint'>interface Extendable {
    public function parseData(mysqli $&database); // Force it to accept a reference to a mysqli object (mysql connection)
    public function displayOnPage();
}
</pre><br />
ok, so to implement this:<br />
<br />
<pre class='prettyprint'>class myPlugin implements Extendable {
    public function anotherMethod();
}</pre><br />
<br />
When you create a new instance of the myPlugin class, it will throw out an error because it doesnt adhere to your interface rules.  Note that I've also told the plugin to use a mysqli object.  This is a proccess called type hinting.  It tells the function what type of data <br />
<br />
Ok, thats all I'll cover this week.  I'm NOT covering inheritence and polymorphism and overloading in this tutorial.  These three are essentially the "strength"  behind classes - and I think you need a full week to understand them.  As always, any questions etc just email or post a reply.<br />
<br />
Thanks!]]></description>
		<pubDate>Tue, 10 Mar 2009 07:32:22 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/204-lesson-6-object-oriented-1/</guid>
	</item>
	<item>
		<title>Lesson 5 - Homework</title>
		<link>http://www.webdevelopforum.com/topic/194-lesson-5-homework/</link>
		<description><![CDATA[Righteo, lets jump straight in shall we?<br /><br /><br />1) Investigate the str_replace function.  <br /><br />2) Using the above function and other thing's you have learnt, design a page and form parser that accepts an email and message and parses it with the following.  It must remove any words that are in an array - such as "&lt;profanity&gt;" etc and replace them with a given value eg "[badword]".  Then return the filtered message for display on screen.<br /><br />3) Write a form, that uses the following fields to accept a user's input, and display their "contact card" for printing ( in the browser).  First name, Last name, Country, Email, website, comment.<br /><br />4) Find out how checkbox data is sent to the server.  Then write a small script that asks a user if they like a list of food items - and then comments on what they don't like ( hint: use associative array to store the food info).<br /><br />Thats all.  Next week I'll we'll start mysql.  At the moment I dont know what everyone is like with understanding database adminstration - so please let me know.<br /><br />Thanks!]]></description>
		<pubDate>Wed, 04 Mar 2009 12:09:45 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/194-lesson-5-homework/</guid>
	</item>
	<item>
		<title><![CDATA[Lesson 5 - HTML Forms & PHP]]></title>
		<link>http://www.webdevelopforum.com/topic/191-lesson-5-html-forms-%26amp%3B-php/</link>
		<description><![CDATA[Hi,<br />This week I'll be showing you how to get user from the data in the form of an HTML form.  I assume that you know HTML - if not then w3schools.org have some fantastic tutorials and references.<br /><br />30 seconds to summarise the basics of HTML forms:<br /><br />&lt;form action="Name Of Script" method="POST or GET" &gt;<br /><br />&lt;input type="text" name ="username" value="value" /&gt;<br /><br />&lt;input type="radio" name="color" value="read" /&gt;<br />&lt;input type="radio" name="color" value="purple" selected /&gt;<br /><br />Ok.<br /><br />So first of all - our form action needs to point to the name of the script which its sending the data to.  Often this is the same page - so you can use the same script to proccess the data ( and maybe if its invalid display the valid stuff again, and only present empty fields for those that werent correct?)<br /><br />The Method is using POST or GET data.  Get sends the data in the URL, so its fairly ( VERY!!!!!) insecure ( and its limited so if your using anythign over a few fields its usualyl easiest and best to go with POST).  An example of GET data in a url is:<br />index.php?field=value&field2=value<br /><br />*For those of you that know about them, Im not worrying about register globals etc for at least a long time <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /><br /><br />So - You've created your form?  Great.  Now - the magic of PHP:<br /><br />&lt;?php<br /><br />echo $_POST['fieldname'];<br />?&gt;<br /><br />PHP magically makes the form available through the $_POST and $_GET arrays (for POST and GET data methods).  Alternatively you can ignore which method it was sent by and use $_REQUEST....  But then you leave yourself even more open to attack ( because anyone can enter a value into the url).<br /><br />So... We have this data - but it could contain anything.  If there is one thing that you learn out of all this ( and hopefully you'll learn more anyway) its that you should NEVER TRUST THE USER!!!! NEVER TRUST THE USER!!! NEVER TRUST THE USER!!!!!  ok.  Got that straight?  See as soon as you trust the user - you let them take advantage of you, they could upload a virus or anything.<br /><br />Instead of just using $_POST['username'] we should 'clean' or parse the data.  For now ( so it doesn't get too messy and it stays nice and simple) I'll use just a few easy functions. Later on when we play with MySQL - we'll need to do more parsing ( more on SQL injection attacks later).<br /><br />echo strip_tags(trim($_POST['username']));<br /><br />As you can see, I have placed a function call in a function call.  This is perfectly legal and is often left like this.  Note that if you embed more than one level into the function arguments  - you start getting really messy unreadable code....  This is fairly ok - and its sort of standard amongst a lot of coders to leave the validation this way.  Note - its pretty much like maths, you do the inside function, and then work your way out.<br /><br />Firstly we trim() the value.. this removes any whitespaces before or after the first characters ( eg " computer" would become "computer").  Then we strip_tags() that value.  This this is a very useful function - it pretty much removes all the HTML and PHP tags from the code.  As a second argument, you can pass it a string of tags to ignore - eg if you wanted to ignore all "&lt;br /&gt;" you would go: strip_tags($variable, "&lt;br /&gt;");.<br /><br />Now... Unfortunately at this time we cannot do too much more ( easily) to validate our values.  If you want to you could pass it through intVal() functions to try and remove string's etc- eg if you wanted an age not a name?  Later on when we have covered regular exp<b></b>ressi&#111;ns (pattern matching etc) we can revisit this and look at validating fields with those ( because this topic is extremely important to any programmer anywhere).<br /><br />Now.  Now seems as good as ever to look at looping through our array.<br /><br />This is a specific loop for use on arrays:<br /><br />FOREACH!<br /><br />foreach($array_name as $field =&gt; $value {<br />    //each iteration sets $field and $value to their respective values in the array.<br />}<br /><br />alternatively you can use:<br /><br />foreach($array_name as $value) {<br />    // here the $field variable is unavailable, but sometimes you only need the value <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /><br />}<br /><br /><br />* If you weren't aware you can create arrays of elements in HTML:<br /><br />&lt;input name='name[]'&gt;<br />&lt;input name='name[]'&gt;<br /><br />then $_POST['name'] is an array:<br /><br />foreach($_POST['name'] as $value) {<br />  // $value stores the value from each of the above fields<br />}<br /><br />This method is especially useful if you need a dynamic length of fields ( eg a list of input boxes such as is on a log of google applications ( email, docs, pages etc).  Alternatively, you might have a set of checkboxes you need to loop through etc.<br /><br />So - I think I'll leave it there this week.  For homework I'll be getting you to write your own little word filter - to filter out bad words.  However more on that tomorrow <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /><br /><br />C Ya<br /><br /><br />P.S. If you want to look at how forms are constructed on sites - a really useful tool is firefox's "web developer toolbar" it allows you to select and view form information (as well as a heap of other stuff). It also allows you to force the form to use POST or GET even if its selected to do the other <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /> - and all sorts of neat stuff like that.]]></description>
		<pubDate>Mon, 02 Mar 2009 16:14:40 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/191-lesson-5-html-forms-%26amp%3B-php/</guid>
	</item>
	<item>
		<title>Lesson 4 - Homework.</title>
		<link>http://www.webdevelopforum.com/topic/184-lesson-4-homework/</link>
		<description><![CDATA[Hi,<br /><br />Ok - instead of having the homework specific to this week's work - here are some things you'll need to know that encompass everything we've done so far.<br /><br />1) Write a isPrime() function, that accepts a number, and returns a boolean - based on testing if it really is a prime number<br />2) Find a way to calculate 10% tax on any given value, and allow for $x amount of "tax free" things.  I'll leave this up to you on how you want to structure it ( as a function or not etc).<br /><br />3) Look into recursive functions ( functions that call themselves ) - and suggest one web-related reason we might use it ( I'll be using this in a few weeks when we cover OOP).<br /><br />4) Later on we'll look at exceptions.  As a primer for that, write a user friendly function you could do if you found an error ( so it will need to display the error, and data about the error).<br /><br /><br />That's it.  If everyone can post in the main/original thread on what feature you want to program first, that will help.  At the moment I'm looking at a simple login form - with or without captcha I'm not sure.<br /><br />C ya]]></description>
		<pubDate>Wed, 25 Feb 2009 10:43:25 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/184-lesson-4-homework/</guid>
	</item>
	<item>
		<title>Lesson 4 - Control Structures</title>
		<link>http://www.webdevelopforum.com/topic/183-lesson-4-control-structures/</link>
		<description><![CDATA[Hi,<br /><br />Well hopefully you all know your variables, arrays and data types - because this is the place that it all comes together ( and we can start programming something useful).<br /><br />First, we have to understand conditions:<br /><br />5==5;<br />Here, we test if 5 is equal to 5 - which is of course true.  That is why that "condition" evaluates to boolean true.<br /><br />10!=14;<br />Here we test if 10 is NOT equal to 14, which is ( again) true.<br /><br />4&gt;9;<br />Is 4 greater than 9?  There are a total of 8 condition (or "comparison") operators: ==, !=, &lt;, &lt;=, &gt;, &gt;=, ===, !==, &lt;&gt;<br /><br />So, the first few are fairly simple to understand:   is equal to, is not equl to, is smaller than, is smaller than or equal to, greater than etc etc.<br /><br />===, what on earth is that?  Well its where you want to test to see if the data type is the same, not just the value:<br /><br />5==="5";<br />That is false, because the integer is not the same as the string, even though they hold the same value ( an == operator in there would return true).<br /><br />&lt;&gt; and != are the same, I personally prefer !=, however its up to you.<br /><br />You can usually test almost anything with the conditional operators, however we usually use variables (or an embedded function call like this (assumes you have written an add() function):<br /><br />add(5,10)==15;<br /><br />So why do I need these comparison operators?  Because not all programs run from A to B without testing something.  For example (in a quite literal sense), you need to see if the lights are green before driving into the intersection.  You need to test to see if the fruit is rotton etc.  After all, a program is designed to do things faster than we do, to automate a proccess....  it needs to make decisions...<br /><br /><br />------------------------------------------------------------------<br />IF  somethign THEN do somethign else.<br /><br />if(5==5) {<br />  echo "Its true!";<br />}<br />else if (9&gt;=10) {<br />  echo "This one is true!";<br />}<br />else {<br />  echo "Everyone is lying today <img src="http://www.webdevelopforum.com/public/style_emoticons/default/tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" />!";<br />}<br /><br />Now of course the code inside the else if will never run - because its condition will always evaluate to false - thus not executing.<br />The else code, runs if nothing "else" was true <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /> - it reads rather nicely don't you think?<br />The thing to note about an if, else if, else structure, is that once one of the conditions are true, it will NOT run any of the others - even if they are true.  If (always) the first IF is true, then the rest of the else if's will not be tested, and it will skip to the end of the "else" code.<br /><br />You can put anythign you want inside these if, else if, else conditions, functions, variables, echo, other conditional statements.... ANYTHING!  You can also have more than one else if, or no else if's.  but you MUST! have the if() if you want to test anything.<br /><br />else if() {} - by itself is invalid:<br />else {} - by itself is invalid ( well there are other times to use an else, however thats for later).<br />if() {} - is fine <img src="http://www.webdevelopforum.com/public/style_emoticons/default/smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /><br /><br />------------------------------------------------------------------<br />SWITCH<br />This is an alternative to the IF statement.  In most cases the IF is best, however SWITCH is designed for use when you are testing the same variable for a number of different values, such as the lowest common factor of a number: (assumes that you have written a function to find such a thing).<br /><br />$number = LCF(19); // this will be 2<br /><br />switch ($number) {<br />    case "correct":<br />        echo "Correct has executed";<br />        break;<br />    case 2:<br />        echo "2 has executed";<br />        break;<br />    default:<br />        echo "Nothign else was true, so this is running";<br />        break;<br />}<br /><br />Notice how I have placed break; at the end of each case.  This is to stop PHP from executing anything else in the case brackets.  If I left off the case, then everything else would be executed.<br /><br />default does the same thing the else does, it runs if nothing else is true.<br /><br /><br />------------------------------------------------------------------<br />FOR (condition), execute code.<br /><br />This loops through code, based on a counter.  eg:<br /><br />for($number=1; $number&lt;=10; $number++) {<br />    echo $number;<br />}<br /><br />This displays the numbers 1-10<br /><br />The contents of the FOR brackets is as follows (it is always 3 arguments).<br />$variable=value //initial value for the loop.<br />condition    // This is the condition that is tested.<br />operation    // This is the operation executed at the end of each loop iteration (each time the loop runs).<br /><br />the ++ increments the value on the left, by one.  if you want to increment it by another operator:<br />$number -= 5; // subtracts 5 each iteration.<br />$number--; // subtracts one each iteration, useful for a countdown loop<br />$number *=$number;   // increments $number by the square of itself each iteration (1,2,4,16,25 etc).<br /><br />------------------------------------------------------------------<br />WHILE something is true, then DO this:<br /><br />This is fairly straight forward:<br /><br />while (condition) {<br />    execute code<br />}<br /><br />This is similar to IF's and FOR's:<br /><br />$array = Array("one", "two", "three");<br />$index = 0;<br />while($index&lt;3) {<br />   echo $array[$index];<br />}<br /><br />This will display the contents of the $array variable  (more specifically it will display the first 3 elements).<br /><br /><br />------------------------------------------------------------------<br />DO this WHILE condition<br /><br />This is almost identical to the WHILE loop, except it will always run the code at least once.  A while loop can ( depending on the condition) never run at all.<br /><br />do {<br />code<br />} while (condition);<br /><br />For example:<br /><br />$incr=0;<br />do {<br />  echo "Hello World!";<br />  $incr++;<br />} while ($incr = 10);<br /><br />Fairly straight forward yes?<br /><br /><br />-- WARNING -- infinite loops!!!!!<br />Watch out for infinite loops.  These loops have no case where it returns false ( thus, running forever).  In some applications ( such as GUI etc.) they are useful, however in almost all web applications they are horrible evil loathsome little cockroaches (not that I have anything against cockroaches of course).  They will run endlessly until PHP's Maximum Execution Time has been exceeded, and the script is forcefully stopped.  For example:<br /><br />while (True) {<br />code<br />}<br /><br />will run endlessly, because it is always True, so: WHILE true, DO code.....   it is always true this never escapes.<br /><br />So, how can we avoid this.... continue and break statements<br /><br /><br />A continue statement skips to the end of the loop, where the condition is tested again.  This is helpful if you have an if() inside the loop, and you want to skip the rest of the code ( such as don't run the code $number is larger than 100).  Granted, that the condition there could and probably should be tested in the initial condition.<br /><br />A break statement "breaks" out of the nearest loop all together, and does NOT test the condition again.  You saw this used in the case, where it breaks to the end of the case{}, skipping any other code.<br /><br />You can call these statements just the same as in the case:<br />continue;<br />break;<br /><br /><br /><br />So... It's all very nice to be able to test one condition, but what if I want to see if the apple is green AND I have enough money to buy it....<br /><br />Well thats where we start making multiple comparisons.  For those familar with C++ etc, && and || is available in PHP, and is indeed my prefered method.  However for those that are more "english" inclined, your script can read very easily when you use the "and", "or" and "xor" comparisons :<br /><br />$apple == "green" and $money &gt;= $cost;<br />$apple == "green" && $money &gt;= $cost;<br /><br />These two are the same, one uses &&, and one uses ||.  Note that if you were to use both && and "and" in the one test, the && would be first, which would be the equivalent of:<br /><br />if(($apple=="green" && $price &gt;= $cost ) and $apple_type=="big and juicy") {}<br />So first, if the apple is green and I can afford it ( which at the moment well assume is true).  Then we test to see if that is true, AND the apply is big and juicy.  This will eventually all evaluate to true. <br /><br />The xor comparison is the equivalent of: "This is true  or that is true, but not both".  So for example you wanted to only buy an apple that is big  OR red, but not BIG AND RED.<br /><br />So if you wanted to test a form, to see if the entrant was male and over 13, then you would use:<br /><br />if($sex=="male" and $age &gt; 13){}<br /><br />and if you wanted to test if the entrant was a male or a female but not both:<br /><br />if($sex=="male" xor $sex="female") {}<br /><br /><br /><br />The last thing Ill cover are two new functions that are part of PHP's internal function library:  isset() and empty()<br /><br />Often you will need to see if somethign is set, for example, has the user uploaded a file (Im not going to use actual variable names here because it may confuse some people):<br /><br />if(isset($uploaded_file) && !empty($uploaded_file)) {}<br /><br />This tests to see that the variable $uploaded_file is set, and that the variable is not empty ( or is not equal to NULL).  This is the prefered method of testing, instead of if($uploaded_file).<br /><br />I hope this lesson has made sense.  I'll be posting the homework soon.<br />Enjoy!]]></description>
		<pubDate>Mon, 23 Feb 2009 07:13:19 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/183-lesson-4-control-structures/</guid>
	</item>
	<item>
		<title>Lesson 3 - Homework</title>
		<link>http://www.webdevelopforum.com/topic/180-lesson-3-homework/</link>
		<description><![CDATA[hi,<br /><br />There isnt really much I can set you for homework this week - that is actually useful.  Once you know more about getting data into your program ( 2 weeks time), then I'll set you some homework about arrays then.<br /><br />As for functions, they are more like a tool than an actual feature to practice ( though many will disagree with me there).  The most useful thing you could do with this weeks lesson is to go back through all our lessons ( 1-3) and make sure you know it.  Next weeks lesson ( ie, 2 days time) I'll be posting about loops and other control structures, and its important you know about your variables, functions and arrays etc.<br /><br />Thanks.<br /><br />]]></description>
		<pubDate>Sat, 21 Feb 2009 04:19:18 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/180-lesson-3-homework/</guid>
	</item>
	<item>
		<title>Lesson 3 - Arrays, and functions</title>
		<link>http://www.webdevelopforum.com/topic/176-lesson-3-arrays-and-functions/</link>
		<description><![CDATA[Hi,<br /><br />Sorry for the delay - I've been pushed for time for the last 4 days, and will be till the end of this week.  But here is Lesson 3:<br /><br />*Edit:  I've rewritten this based on a few points made by Peter (my mistakes etc <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />)<br /><br />Arrays:<br />These allow you to group adata into a sort of list.  Its extremely useful for storing pairs of data, in the format of "key"="value".<br /><br />&lt;?php<br />$list = Array();<br />$list[] = "value1";<br />$list[] = "value2";<br />$list[] = "value3";<br />echo $list[2];    // displays "value3"<br />?&gt;<br /><br />Now, whats this [] you ask.  Well its the way you call your data, better known as the index.  Think of the Array as a sort of simple dictionary.  You store the word in the key, and then definition in the value... The index can either be a string or an integer, if you try to use another data type, (dependign on the type) it will throw out an error ( index out of bounds from memory).<br /><br />You can also define thes key=value pairs inside the Array() function itself:<br /><br />&lt;?php<br />$list = Array("key"=&gt;"value");<br />$list["string1"] = "Hello World!";<br />?&gt;<br /><br />This will create the array:<br />$list["key"] = "value";<br />$list["string1"] = "Hello World!";<br /><br />Now if you were to create an index (with a strign index) that did not use quotes... It will work, however (thanks Peter) it will try and find a constant with the same name first (I'll cover constants later on).  As a general rule, you want to define keys with a string (usign quotes).<br /><br />The value of an array can be anything you want, string, integer, float, MySQL object etc.  Better still you can have it as an Array; its surprisingly useful to have an array of arrays.  It creates a sort of grid... Think of storing a table of results etc.<br /><br /><br />Functions:<br />Functions are really good at doing "stuff".  You tell the function what you want it to do, and with what data - and then you can use it wherever and whenever you want ( granted you have defined it in the script <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />).<br /><br />For example:<br /><br />&lt;?php<br />//This function adds 2 numbers together<br />function add_numbers($number1, $number2) {<br />    return $number1 + $number2;<br />}<br />echo add_numbers(4,5);<br />?&gt;<br /><br />As you can see, I define the function, and what I have to pass it.  Then I tell it what to return.  When a function returns a value, you can sort of think of it as the actual value of the function.  * Note that it isnt the value, but its sort of like it*.  In the end, its what the function evaluates as - so if you put it into an exp<b></b>ressi&#111;n ( like I did when I called it on the last line above), thats what it equates to.<br /><br />As with most variables, you can use functions to do anything to anything....    Its an alternative to copying and pasting code where you want to reuse it.  Think of the above function.. (for exanple purposes only of course...)  See if you wanted to repeat that code multiple times in your script, you could copy and paste it wherever  you want it.  However think what woudl happen if you accidently made a mistake without realisign it 0- you woudl have to find each location you copied it to and fix it manually.  Instead you can run that code in a function - writign it only once, and then you call the function, which is much much much (etc) better!<br /><br />Well thats all - ll put hyomework online tonight, and last weeks answers up soon.<br /><br />Thanks for your patience!<br /><br /><br />]]></description>
		<pubDate>Wed, 18 Feb 2009 11:06:21 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/176-lesson-3-arrays-and-functions/</guid>
	</item>
	<item>
		<title>Lesson 2 - Homework</title>
		<link>http://www.webdevelopforum.com/topic/151-lesson-2-homework/</link>
		<description><![CDATA[Hi,<br /><br />Firstly sorry this is late, I've been flat out for the last 2 days.   But here it is  (for those that have been waiting).<br /><br />I'm mainly focusing on making sure you understand dates and formatting....  so thats what I've based it on.  I have only got 5 questions this week + a small task to help us get towards the larger project.<br /><br />1) Place the following 3 values into variables.  Find the average value and format it like: $123,456.78<br />$190000<br />$6000<br />$17000<br /><br />2) Find the timestamp for 13/2/09 at 13:45:14.<br /><br />3) Find GMT time (using time and date functions (php website)), for 2pm on saturday 14'th February 2009 (this saturday).<br /><br />4) Find the first character position of "gcat" in the following string:<br /><br />"""<br />gatacaccatgatgagctgattacagatagacaggcatcgatgatgctagtgctgaatcgcggctcgatataatagtcgt<br />a<br />"""<br /><br />5) If I have 5 chickens, each worth $4 each in a pair, but only $3 when sold seperately, figure out ( using PHP's math functions) how much I will ean if I sell the maximumn number of "pairs of chickens".  Then format that as "$123.00"<br /><br />6)  This is a more "practical" thing to work on.  On most forums, and websites in general you will often see when somethign was posted - a very practical use of timestamp formating.  I want you to come up with the date string ( to format the timestamp into a human readable string), in order to duplicate the formatting of times on this site:  eg, the forum posting time for Lesson 2 was: "Feb 10 2009, 12:07 AM".  GDLK!  Hint:  If you cant seem to get upper case or lower case, you may have to go back to your string formatting functions <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />.<br /><br /><br />Thats all for now, but as always you can reply here or email me for help etc.]]></description>
		<pubDate>Wed, 11 Feb 2009 13:32:18 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/151-lesson-2-homework/</guid>
	</item>
	<item>
		<title>Lesson 2 - Working with data</title>
		<link>http://www.webdevelopforum.com/topic/147-lesson-2-working-with-data/</link>
		<description><![CDATA[Hi,<br /><br />As the Topic Description says, this lesson really does build on your understanding of the first lesson (and to a certain extent the homework.)  If you haven't already, I recommend you read through the first lesson, and at least read through the homework and answers.<br /><br />Ok, so I'll break this into 4 sections, maths, string and number formatting, modifying string, and dates.  Each one is fairly unique in itself, so I hope you enjoy!<br /><br />Maths<br />______________________________________<br /><br />Ok, so we all know that 1+1=2, but how do we program it?  Well there are 5 math operators (yes 5 not 4).  These are +-/* and %.<br /><br />+ or the addition operator is pretty much self explanatory in what it does.   As is -.  generally you would use them like:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$variable = 2+2; // equals 4<br />or<br />$variable = $val1+$val2;<br />and subtraction&#58;<br />$variable = 3.14159 - 9.51413;&nbsp;&nbsp;// equals -6.37254<!--c2--></div><!--ec2--><br /><br />The next two operators, / and * are division and multiplication respectively.   <br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$x = 4*5*10; // equals 20<br />$y = $x/50; // equals 4<!--c2--></div><!--ec2--><br /><br />Like most simple maths equations, you can have as many terms as you want in the statement.  In addition to this, php handles your order of operations normally:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$a = &#40;&#40;1+4&#41;*5&#41;/0.5; // equals 50.<!--c2--></div><!--ec2--><br /><br />Now, the almighty modulus operator, or %.  This returns the remainder from the division of the two terms:<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$remainder = 9%2; // $remainder will store the value &#40;int&#41; 1.<!--c2--></div><!--ec2-->  <br /><br /><br />Now, to put all of these together:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$y = &#40;3*3*3&#41;/12 + 9%4; // which equals 4.<!--c2--></div><!--ec2--><br /><br />Now, there are a few maths functions which are very useful, these are:<br /><br />sqrt($x); // returns the square root of $x<br />pow($x, $y); // returns $x to the power of $y<br />I wont mention all of them here, however there are other mathematical "functions" such as cos, sin, tan, floor, ceil and round - all of which are useful (especially if your doing geometrical work).<br /><br />Math constants:  These are preset values within PHP and can be used just like a variable ( however you call them without the the "$".<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->M_PI; // pi or 3.14159<br />M_E; // e or 2.718<!--c2--></div><!--ec2--><br /><br />There are many others, like specific approximations of Pi, and other static values that are commonly used.<br /><br />So to use these constants in a line of code:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$Area = M_PI*pow&#40;$radius, 2&#41;; // returns the Area of the circle with a radius of $radius<!--c2--></div><!--ec2--><br /><br /><br /><br />Math and String formatting<br />______________________________________<br /><br />To format a number, you use the number_format() function,  which accepts a number and some formatting values ( such as commas and decimal points) and returns a string of the formatted number.  Its 4 arguments are as follows:<br /><br />number_format ($number, $number_of_decimals, $decimal_serperator, $thousands_seperator);<br />More complex number formatting can be<br />Which can be used like this:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->format_number&#40;104500.99, 2, &#34;.&#34;, &#34;,&#34;&#41;; // 104,500.99<!--c2--></div><!--ec2--><br /><br />More complex formatting of any string or number can be done by using printf() and sprintf().  The difference between the two is that sprintf() returns the value, but printf() displays the value.<br />Here's one I prepared earlier:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$money = sprintf&#40;&#34;%05.2f&#34;, 123&#41;; //123.00<!--c2--></div><!--ec2--><br /><br />Here, % tells it to start parsing formatting. 0 is the padding, if the length of the number/string is shorter it is padded. After this I can add a "-", which tells it to pad on the left instead of the right which is default.  Then comes a 5 or other digit which  specifies the width of the number formatted.  If its shorter than this number, then the padding is used.  ".2" tells it to use 2 decimal points, and f says a float instead of s which is a string.  I personally find that I don't have to use formatting much more complex than this  - and if I do I can always look up the formatting reference on php.net <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /><br /><br /><br /><br />Manipulating strings<br />______________________________________<br /><br />There is a myriad of string functions, so I cannot cover them all here.  However there are a few very (very) useful ones that I often use regularly.  The first is explode()!.  This function takes 2 arguments, a string input, and a string delimiter.  It returns an array of strings, that has been split at the delimiter (I'll be discussing Array's next week).  eg:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$words = explode&#40;&#34;This is a string!&#34;, &#34; &#34;&#41;;<!--c2--></div><!--ec2--><br />will return:<br />"This", "is", "a", "string!".  From this (and well cover the array functions next week) you could count the length of the array to find the number of words.  Of course there is already a PHP function to count the words in a string, however you can already see a useful application of explode.<br /><br />substr(), returns a sub string of the one passed into it.  eg:<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$word = substr&#40;&#34;words are cool!&#34;, 0, 4&#41;; // &#34;word&#34;<!--c2--></div><!--ec2--><br /><br />Now this is probably a good time to explain string indexing.  Most programming languages start counting at 0 and not 1.  For this reason, the first character has the index of 0, the second character index 1, and so on so that the nth character has n-1 as its index <img src="http://www.webdevelopforum.com/public/style_emoticons/default/smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />.     So this function accepts a string, a starting character position ( 0 for the beginning), and a length - in this case 4 characters.<br /><br />You can also use negative indexes.  -1 refers to the last character, so substr("str" -1, 1); would return "r".  <br /><br />strlen("string");, very simple - returns the length of the string, in this case (int) 6.<br /><br />Some functions that I use less often but are still useful include str_replace, which accepts a string, a sub string and a replacement sub string and it searches the string, for any occurrences of the sub string, replacing them with the specified replacement.  Although this does seem to be very useful I usually use a regex/pattern approach using the preg_ functions....   Regex (or Regular Exp<b></b>ressi&#111;ns) are a mini-language in themselves, specicially designed for pattern matching.  They are extremely useful for searching log files for specific patterns ( say, a given connection that occurs at 8 am every day for 10 weeks might mean something).  In addition we will look at them when we look at validating input - making sure the user isn't hacking our system <img src="http://www.webdevelopforum.com/public/style_emoticons/default/smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />.  Anyway, back to str_replace,  it has a more simplified approach and usually you will find a regex approach is much more robust.<br /><br />str_pos() and substr_count() return the first occurrence of given sub string, and the location of the sub string respectively - often are very useful for seeing if a certain string is in there ( eg, seeing if a user name contains "admin" at all - in order to ban it).<br /><br />That's most of the extremely useful ones.  In about 4-5 weeks we can start to use these functions in practice on our first mini-project <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /><br /><br /><br /><br />Dates<br />______________________________________<br /><br />Ok, sooner or later you will have to work with dates.  More specifically youll have to work with Unix Timestampes.  These are essentially really ( fairly) large numbers, that each computer counts - its the number of seconds since Jan 1970 00:00:00.<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$now = time&#40;&#41;; // Whatever the current timestamp is.<!--c2--></div><!--ec2--><br /><br />This might equal something like 1234183142 (which was the timestamp when I ran the code on my server).  <br /><br />Once you have a timestamp, you'll want to be able to format it for your users - after all I know personally that I cannot tell the time in seconds from 30 years ago <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />.  To do this we use the date() function.  Its similar to sprintf(), in the sense that it accepts a value, and a formatting string.<br /><br />Here we go:<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->date&#40;&#34;l n/F/Y G&#58;i&#58;s&#34;, $timestamp&#41;; // &#34;Tuesday 09/02/2009 23&#58;45&#58;56&#34;<!--c2--></div><!--ec2--><br /><br />If you do not tell it what $timestamp you want, it assumes the time(), or the current time.  Now there is a large table which explains what each character means however in short each letter stands for a part of the time, and the other "/" " " ":" characters are there for formatting.  Think of it as though for each letter in that string, it is str_replace()ed with the correct value <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />.  l is the day of the week, n/F/Y is day/Month/Year and then you have G:i:s meaning Hours:Minutes:Seconds.  You can specify with or without a leading 0, 12 or 24 hour time, am/pm etc, just place it in your string <img src="http://www.webdevelopforum.com/public/style_emoticons/default/smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />.<br /><br />Now, what if we don't know the timestamp, but we know the date values.  Well we can use mktime(), who's arguments are the following:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->mktime&#40;hour,min,sec,month,day,year&#41;; // All of which are &#40;int&#41; values<!--c2--></div><!--ec2-->.<br /><br />This will store the timestamp, same format as time().<br /><br />Ok - and say you want to be programmer friendly, or your just lazy <img src="http://www.webdevelopforum.com/public/style_emoticons/default/tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" />.  You know that you want the timestamp for 1 hour's time.... do you really want to have to get now and add 60*60 (60 seconds in a minute, 60 minutes in an hour) ?  No?  Well firstly shame on you <img src="http://www.webdevelopforum.com/public/style_emoticons/default/tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" />.  No not really - because PHP has already come up with a solution:<br /><br />strtotime().  You place in a string describing the time you want, and you get the timestamp out, heres an example:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$tomorrow = strtotime&#40;&#34;tomorrow&#34;&#41;;<br />All of the following strings will work&#58;<br />&#34;Yesterday 3pm&#34;<br />&#34;now + 6 hours&#34;<br />&#34;next year&#34;<br />&#34;5 minutes ago GMT&#34;<!--c2--></div><!--ec2--><br /><br />Now, I've added an interesting thing in the last one - a Timezome definition.  Its not always 4pm around the world is it!  So PHP goes on wherever the server's time/timezone is set to.  Say for example you are running a website ( such as this one) who's members come from all over the world.  It can get very confusing when the most recent post (5 minutes ago) was posted at 3 am, when its 6 pm for the user!.  Well this happens when the server works at 3am, but the user is in a different timezone.  Now I personally haven't perfected the method of storing timestamps.  Usually I prefer to convert all timestamps into GMT - so that I can then convert them to any time I want.  It can definitely get confusing and you will have to read through some of PHP's documentation to make sure that your own method or storing is correct etc.  Either way - be aware that even if your local time may be 6 pm, the server might be on the other side of the world ( as was the case for my shared server before I purchased one hosted locally).<br /><br />Just a small addition, you can easily find the difference between two times.  Say for example you have two dates, and you need to find how long between them.  simply subtract one from the other - and you have it <img src="http://www.webdevelopforum.com/public/style_emoticons/default/smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />.  Another thing to remember is IT IS ALWAYS IN SECONDS.  So if you wanted to add 1 day to a time without using functions ( which is often easier because you dont have to worry about timezones that way), you must add 60*60*24, which is 60 seconds per minute, 60 minutes per hour, 24 hours per day.  <br /><br /><br />Woah!!!  That was a lot for one lesson.  To be honest, a lot of this stuff here can easily be looked up on the PHP website and the sooner you learn to do so the less youlul have to remember.  Eventually as you begin to program in PHP more often - you'll find that you remember your own personal set of favourite functions, because there is not always only one way to achieve something - especially with strings.<br /><br />Depending on the feedback I get this week, I may place Array's and functions into the one lesson - but if no one tells me how your going, then I won't because I don't want to speed ahead leaving people behind.  Just for reference until I do teach functions - while looking up how to format strings etc, you are all using functions.<br /><br />Functions (A 30 second overview).<br />A function does something.  It might add one number to another, or it might accept a form and process it into a database, emailing the web master of a new entry.  Either way its still doing "something".  to call a function it is:<br /><br />function_name ($argument1, $argument2.......);    where the function name is (obviously) the name of the function such as "explode" or "substr".  the $arguments, are values that you pass into the function.  Generally, a function only knows about data you send into it using arguments.  Some functions have optional arguments, such as date() where if the second argument isn't actually used, it makes the assumption of a certain value.  Hopefully that will clear up a few things when your looking around PHP's function reference ( Text section, Strings subsection) - or <a href="http://au.php.net/manual/en/ref.strings.php" target="_blank"><a href='http://au.php.net/manual/en/ref.strings.php' class='bbc_url' title='External link' rel='nofollow external'>http://au.php.net/manual/en/ref.strings.php</a></a> to be specific.<br /><br />Do look around the just named website, read through this again - and let me know if you have any problems.  If I don't get any feedback I'll assume that everyone's fine and I'll post homework.<br /><br />Thanks ( and goodnight!!!!),<br />Jack<br /><br />]]></description>
		<pubDate>Mon, 09 Feb 2009 13:07:09 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/147-lesson-2-working-with-data/</guid>
	</item>
	<item>
		<title>Lesson 1 - Homework</title>
		<link>http://www.webdevelopforum.com/topic/127-lesson-1-homework/</link>
		<description><![CDATA[Hi,<br /><br />Righto - so I wanted to clear a few things up after the lesson.  Firstly, heres how my current lesson timing runs (it's based on my local time with AEST (gmt+1100)).  Monday evening I'll post the lesson for that week.  Tuesday evening (now) I'll post the actual homework for that week.  That gives roughly 24 hours to let me know if you have got any questions or issues with the lesson.  In the lessons I'll cover the basics of what you need to know ( e.g. data types).<br /><br />Home work is designed to not only "teach" you how to do things, but where to find the information if you're not able to post on forums, or on IRC etc.  Often it'll be finding the exception to a rule, or listing more options (other unused options etc) than what I've explained.  Although you should be able to know PHP fairly well without completeing the homework, I really recommend you do it because it will help your understanding, and it will be that little thing that makes things click in your brain.<br /><br />________________________________________________________<br /><br />So - To lesson 1's homework.<br /><br />In the lesson yesterday, I covered the basics of data, and variables.  Below are 10 questions to get you understanding the specifics of strings, and other data types.<br /><br /><br />1) List 4 different ways to create and/or display a string.<br />2) What is the output from the following code? Suggest an example where it might be useful to use that method.<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->&#60;?php<br />$variable = &#34;Hello!&#34;;<br />$name =&#34;variable&#34;;<br />echo $$name;<br />?&#62;<!--c2--></div><!--ec2--><br />3) What does the following code do/display, and why it might be useful? (This is a very important feature of PHP).<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->&#60;?php<br />$foo = 3.14159;<br />echo &#34;4 cows&#34; + $foo;<br />?&#62;<!--c2--></div><!--ec2--><br />4) Create 2 variables, and find a way to join them together to make one string, save it in a variable and then display it all in uppercase. (hint:  look into using PHP functions, though we haven't covered function use so its a "bonus mark").<br />5) Why doesn't the following code work, and how can I fix it?<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->&#60;?php<br />echo &#34;&#092;&#092;&#34;;&nbsp;&nbsp;&nbsp;&nbsp;//Hint,&nbsp;&nbsp;I want the output to be 2 backslashes one after the other<br />?&#62;<!--c2--></div><!--ec2--><br />6) Explain what the following data type is, and how I can make it a number (integer).<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->&#60;?php<br />echo 0x1B;<br />?&#62;<!--c2--></div><!--ec2--><br />7) Why doesn't the following code round the number as expected?<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->&#60;?php<br />echo &#40;int&#41; 4.9;&nbsp;&nbsp;// Expected output is &#34;5&#34;<br />?&#62;<!--c2--></div><!--ec2--><br />8) What do the following data definitions have in common?  Note that if you type this into a PHP page, it will cause an error ( its not 100% correct code).<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->&#60;?php<br />&#34;string&#34;<br />1<br />true<br />-1<br />?&#62;<!--c2--></div><!--ec2--><br />9) What is a NULL value and when/why is it used?<br />10) Is this homework too hard, and did you want it to be easier <img src="http://www.webdevelopforum.com/public/style_emoticons/default/tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" />?<br /><br />That's it.  For now, I'll suggest that you look around on the PHP website, in the documentation pages....  <br /><br />As I mentioned above, I'm not at all expecting you to complete all the homework, nor am I going to ignore it.  If you do want to do it or some of it, I'll go through it and "mark" it, and help each of you individually in explaining the answers to anything you couldn't find etc.  If anyone feels protective of their code etc (i.e., you don't want to post a copy of your work on the forum) you can email me the code when its complete etc.  Please post on the forum when you have emailed me the homework so I can make sure it doesn't go to spam etc.  Because of the above reason for homework, I'm not setting a due date as such, but I reccomend you look at it if you are going to, before the next lesson (because just like maths, each lesson will build on the previous).  jack@battleages.com is my email - so pretty much do it, send it, ill get back to you and we can get working !!!  Just a note though, if you could send the answers as the email body and not as an attachemt (.doc .pdf etc) then that would help a lot.  It's easiest for me because I can reply back with "edits" to the code immediately without having to download, open, edit, save etc <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /><br /><br /><br />As always, I'm available on msn or through email - but please post here if you have any questions regarding the homework.<br /><br />Thanks and happy researching,<br />Jack]]></description>
		<pubDate>Tue, 03 Feb 2009 11:38:30 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/127-lesson-1-homework/</guid>
	</item>
	<item>
		<title>Lesson 1 - Data and Variables</title>
		<link>http://www.webdevelopforum.com/topic/120-lesson-1-data-and-variables/</link>
		<description><![CDATA[Hi,<br /><br />Firstly thanks for such a warm welcome, I hope these will live up to your expectations.<br /><br />Secondly, I want to set out a few prerequisites.  I am assuming that you're using PHP as a web server addon (cgi or the like).  If you want to use PHP as a command line language ( many *nix people might want to do this) then you can, with a few minor changes which I will not be covering.  The easiest method for getting PHP on a web server on windows is through using XAMPP (google it).  I won't cover an installation/configuration tutorial unless I get a few people wanting one.<br /><br />In this lesson I'll be discussing the different data types, and how to use them with variables and output.  I'm assuming no knowledge of any programming languages so I'll start at the beginning.<br /><br />In the most basic form, your websites, scripts and programs will accept data and display information back to the user.  Your data might be a username, and your information could be a welcome message.  More complex scripts might process the data, such as searching a database or analyzing the data to create graphs etc.<br /><br />So what is data?<br />Well, in PHP it usually comes in 4 main forms: Strings, Integers and Floating Points (floats) and Booleans.  A String contains a group of characters, and is identified with "". eg. "This is a string".  Integers are your basic whole numbers:  1,10, 100, -1000 etc.  Your floating point number or "floats" are decimal numbers, 0.56, 95.877 3.14159 etc.  And Booleans are one of two values:  True and False.  A Boolean value is the most basic form of data, and we usually use it to set flags(which I'll explain in a later lesson).<br /><br />Now, in PHP the basic code structure is:<br />[statement];<br />There MUST be a semicolon at the end of a statement or PHP will spit out an error.  This is probably the most common error in PHP especially for people new to PHP (I still fall victim to it sometimes).<br /><br />The last piece of information you need before we try some code is how to display things back to the user.  Most people use the "echo" statement.  its used in the form of<br />echo [what];<br /><br />So - to our first piece of code:<br /><br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->&#60;?php<br />echo &#34;Welcome to PHP, you have coded your first piece of code.&nbsp;&nbsp;Well done!&#34;;<br />?&#62;<!--c2--></div><!--ec2--><br />Note the &lt;?php and ?&gt; "tags", these tell the web server that the PHP interpreter needs to be called on the file.<br />Place that code into a php file (lesson1.php, for example) and place it in a web accessible location on your server.  When you navigate to it in your web browser, you should see the output:<br /><!--quoteo--><div class='quotetop'>QUOTE </div><div class='quotemain'><!--quotec-->Welcome to PHP, you have coded your first piece of code.  Well done!<!--QuoteEnd--></div><!--QuoteEEnd--><br /><br />Now, variables <img src="http://www.webdevelopforum.com/public/style_emoticons/default/smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /><br /><br />"So what, I can process data but where can I store that data?" you ask.  Well,  that's where we use variables.  Variables are a means of referring to the data; you can store, change and remove data from a variable, create new ones and remove old ones.<br /><br />In PHP we use the $variableName to identify a variable:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$a = 1;<br />$b = &#34;string&#34;;<br />$c = 3.14159;<br />$d = True;<!--c2--></div><!--ec2--><br />All of these are storing the value into the variable.  If we wanted to do something with $a, we could simply call it as "$a" wherever we wanted:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->&#60;?php<br />$name = &#34;Jack&#34;;<br />echo &#34;Welcome $name, This was created using PHP&#34;.<br />?&#62;<!--c2--></div><!--ec2--><br /><br />Now, next lesson I'll be discussing in more detail bout string concatenation, and using variables in strings etc. but as you can see, its simply and easily replaced $name with "Jack".<br /><br />Now, there a few rules about variables, some are enforced by PHP (it will spit out an error if you break the rule), and some are what we call "coding style" or good programming practice.  Firstly, variables can contain any alphanumeric characters, as well as "_" and "-".  You will no doubt come up with your own coding style, however here are a few examples:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$CamelCase<br />$unknownName<br />$thisisveryanoying<br />$USUALLYRESERVEDFORGLOBALS<!--c2--></div><!--ec2--><br />Now as you can see, the two that are easiest to read are the first two, camel case and (forget-its-name).  Variables that are entirely uppercase resemble global variables and arrays ( which well cover later on), and thus, can easily be confused:<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->$SERVER=&#34;apache2.2, php5, mysql5.2&#34;;<br />echo &#34;My server is $_SERVER&#34;;<!--c2--></div><!--ec2--><br />The $_SERVER variable (which is technically an array) is set by PHP/Apache and contains information about the server, however if you wanted to use a variable to store custom information about a server, then you can see the similarities between the two.<br /><br />When we cover more material such Object Oriented Programming (or OOP for short) you'll start to see exactly how important a good variable naming practice comes to be.<br /><br />Please, with all my lessons (this one being no exception) give some feedback on how they are going.  I do want to know if there isn't enough in each lesson, or if there is too much.  If you want more examples, or more explanations then do say because I'm not telepathic <img src="http://www.webdevelopforum.com/public/style_emoticons/default/wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />.<br /><br />Next lesson (for those that want to know) I plan to look at comments, and more use of strings (and other data types).  After we've covered a lot of the basics such as functions, control statements and basic data processing then I plan to come back to coding style because it is ESSENTIAL that you develop one and develop a good one.<br /><br />For those that want some, I'll come up with a small 'research' or 'homework' activity each week (probably posted the day after the lesson) and it will help you understand a little more about what I've covered.<br /><br />Lastly (yes, there's a few post-lesson notes), one of the best sources for information on PHP is the PHP manual.  you can find it under the documentation link at php.net, and its been a fantastic reference and tutorial for me.  Not only is there documentation and basic examples for every function and feature of PHP, but on most pages there is user generated examples which can show you some real life uses of whatever the page covers.<br /><br />Thanks,<br />Jack]]></description>
		<pubDate>Mon, 02 Feb 2009 10:16:01 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/120-lesson-1-data-and-variables/</guid>
	</item>
	<item>
		<title>Test post:  PHP Lessons running</title>
		<link>http://www.webdevelopforum.com/topic/115-test-post-php-lessons-running/</link>
		<description><![CDATA[Hi all!<br /><br />I'm going to be posting here weekly with a new lesson in PHP.  If anyone is interested, please participate in the polls each week, as its the best way to give me feedback.<br /><br />For each lesson, I'll post a new topic containing the material for the lesson, examples discussions and anything else I think you'll need to learn that aspect/feature of PHP.  If you have any questions, need help with code or anything else related to a lesson just post a reply and I'll attempt to get back to you ASAP.<br /><br />A little about me:<br />I've been learning/using PHP for over 3 years, and have made quite a range of things.  I've been working on a game development/management CMS, and have a lot of experience in MySQL related programming (which includes dynamic content, user registration tracking loging etc.  If you've any questions etc. feel free to email.<br /><br />I'm going to start off with the basics (of course) however once we cover those I'd like some input from everyone following the lessons, so that I can try and focus them on what your interested in.<br /><br />If you've got any questions about the course, please reply to this thread.  The board is locked, so that only new lessons by me can be created, but you can reply to them whenever you want.  If you've got any personal questions, please email me: jack@battleages.com.  If MSN is the prefered method of chat then I'm on there as well: Gimli_legs@msn.com.  Note that emailing and MSN isnt always the best way to contact me, I wont always be able to reply to those instantly.<br /><br />Many thanks and happy coding,<br />Jack]]></description>
		<pubDate>Sat, 31 Jan 2009 03:27:34 +0000</pubDate>
		<guid>http://www.webdevelopforum.com/topic/115-test-post-php-lessons-running/</guid>
	</item>
</channel>
</rss>