PHPMule.com Blog
PHP for beginner’s
Welcome to PHPMule.com
A blog site which I am posting to during my learning of the popular programming language PHP. Feel free to leave comments!
-
PHP - Using Loops With Arrays
There’s an even better way of displaying a numerical array’s contents by using a loop because the array is basically indexed by numbers.
We can use a ‘for’ loop to do this:
for ($counter = 0; $counter<10; $counter++) {
echo $celebrity_array[$counter] . ” “;
}
There’s another loop which you could use which was designed for arrays in the first place and that’s the ‘foreach’ loop:
foreach ($celebrity_array as $action_heroes) {
echo $action_heroes. ” “;
}
Here is a while loop that uses the each construct.
while ($variable = each($numbers)) {
echo $element['key'];
echo ” - “;
echo $element['value'];
echo “<br />”;
}
(Post created on Monday, April 13th 09 at 14:15)
-
PHP - Accessing And Replacing Array Contents
To access the contents of an array, you use it’s variable name along with its key (index) such as:
$celebrity_array[0]
so you can use it’s contents.
You can use array variables as you would with normal variables and you could easily change it’s contents by using the ‘=’ operator like the following example:
$celebrity_array[0] = ‘Daniel Craig’ ;
This line will change the contents of [0] to Daniel Craig. It was Bruce Willis by the way but now he’s gone…
(Post created on Friday, April 10th 09 at 23:35)
-
PHP - Using Arrays (Numerically Indexed)
An array is a variable that can store a set of values.
Numerically Indexed Arrays
If you wanted to store a set of values in one variable we could do that as follows:
$celebrity_array[0] = “Bruce Willis”;
$celebrity_array[1] = “Arnold Swarzennegar”;
$celebrity_array[2] = “Matt Damon”;
$celebrity_array[3] = “Liam Neeson”;
If we then wanted to reference to this we could use these lines:
echo “A well known action hero is ” . $celebrity_array[0] . ” and ” . $celebrity_array[3] . ” is pretty good as well! “;
You will also notice that the counter starts at ‘[0]‘ and it’s something you would have to get used to if you haven’t seen an array before.
Arrays obviously save time and it will make your code look a little tidier. I will go more into arrays in the next blog post as I’m still learning
(Post created on Thursday, April 9th 09 at 15:35)
-
Making A Comments Form (Part 2)
Now we have created our comments form (See here: Making A Comments Form) we now need to add a bit of code to the PHP so it can be stored and retrieved later on.
You can store data in two ways:
By using a flatfile;
or using a database.
As i’m learning PHP I ain’t sure which ones best for your needs but having a database is best to store mass amounts of comments where as a flat-file is best for storing less amounts of data and obviously depends on what you need it for. The following file I have modified so any comments my visitors made could be retrieved later on by opening up the comments.txt file.
<?php
$firstname = $_POST['firstname'];
$emailaddress = $_POST['emailaddress'];
$comments = $_POST['comments'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$date = date(’H:i, jS F Y’);
?><html>
<head>
<title>Process Comment</title>
</head><body>
<?php
echo “<p>Following comment sent: </p><br />”;
echo “First Name: ” . $firstname . “<br />”;
echo “Email Address: ” . $emailaddress . “<br />”;
echo “Comments: ” . $comments . “<br />”;
$outputstring = $date.”\t”.$firstname.”\t”.$emailaddress.”\t”.$comments.”\n”;//File will be opened and be appended to
@ $fp = fopen(”$DOCUMENT_ROOT/../comments.txt”, ‘ab’);
flock($fp, LOCK_EX);
if (!$fp) {
echo “<p><strong>Your comment can’t be processed at the moment, please try submitting again later</strong></p></body></html>”;
exit;}
fwrite($fp, $outputstring, strlen($outputstring));
flock($fp, LOCK_UN);
fclose($fp);
echo “<p>Comment submitted.</p>”
?>
</body>
</html>
You will notice the new variable: $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
You will need this line as it tells the script where the source of the file will be when you write to it.
Another new line I have added is: @ $fp = fopen(”$DOCUMENT_ROOT/../comments.txt”, ‘ab’);
This line is created so you don’t have to create the file path of the whereabouts of the file. This will be used again… The ‘@’ symbol tells PHP to supress any errors so you don’t get those horrible messages! The ‘ab’ at the end means append to the file if your wandering.
The next line: flock($fp, LOCK_EX);
This line is used so it disables other visitors from posting a comment at the same time by locking the file. I think there is more of a practical way of handling files later but I haven’t learnt how to do that just yet..
You will then notice these lines in the script:
if (!$fp) {
echo “<p><strong>Your comment can’t be processed at the moment, please try submitting again later</strong></p></body></html>”;
exit;What this does is that if an error is found when sending the comment, it produces that error message and then exits the script.
The next line:
fwrite($fp, $outputstring, strlen($outputstring));The fwrite means to write to the file obviously. You will have come across the $fp variable (the file location), the $outputstring has all the variables such as $emailaddress which are sent to the file. The third bit of this line ’strlen($outputstring)’ avoids cross-platform issues when sending the comment basically.
After the comment is sent, it is required to unlock the file so that another visitor can send a comment by using this line: flock($fp, LOCK_UN)
and then close the file itself by using this line: fclose($fp);
It’s a complex process I know (the whole comment thing actually) probably because I’m a beginner at this stuff so I would recommend looking around the web to find a better way of learning the process (which is what I did!)
(Post created on Tuesday, April 7th 09 at 14:55)
-
Making A Comments Form
I have been experimenting with PHP over the last couple hours trying to design a comments form. By the way I am the newbee of newbies at this stuff so it takes a while to know the concepts!
Well here goes:
<html>
<head>
<title>Comment Form - Submit your comments!</title>
</head>
<body>
<form action=”processcomment.php” method=”post”>
<table border=”0″>
<tr>
<td>First Name: </td>
<td align=”left”><input type=”text” name=”firstname” size =”20″ maxlength=”20″ /></td>
</tr>
<tr>
<td>Email Address: </td>
<td align=”left”><input type=”text” name=”emailaddress” size =”30″ maxlength=”30″ /></td>
</tr>
<tr>
<td>Comments: </td>
<td align=”left”><input type=”text” name =”comments” size =”100″ maxlength=”100″ /></td>
</tr>
<tr>
<td colspan=”2″ align =”center”><input type=”submit” value=”Submit Comment” /></td>
</tr>
</table>
</form></body>
</html>This is the comments form that I created. (Using HTML, PHP Script to follow) This will be a basic comments form to take the first name, email address and obviously their comments. You will notice that the form’s action contains the file name “processcomments.php”. This is the file that get’s processed once the submit button on the form is pressed.
The following file contains three global variables. (e.g. $_POST['firstname'] ) You might notice that the value your visitor sent when they entered their ‘firstname’ will now be the variable and therefore can be controlled in the processcomments.php script. Same goes with their emailaddress and comments.
Here is the processcomments.php file:
<?php
$firstname = $_POST['firstname'];
$emailaddress = $_POST['emailaddress'];
$comments = $_POST['comments'];
?><html>
<head>
<title>Process Comment</title>
</head><body>
<?php
echo “<p>Following comment sent: </p><br />”;
echo “First Name: ” . $firstname . “<br />”;
echo “Email Address: ” . $emailaddress . “<br />”;
echo “Comments: ” . $comments . “<br />”;
?></body>
</html>
When you press the ‘Submit Comment’ button this file is opened and will output this to the browser:
Following comment sent:
First Name: Nathan
Email Address: admin@phpmule.com
Comments: My very first comments box!Although it say’s it’s sent, it’s actually not until we add a bit more code… Will add how to do this in the next blog post!
(Post created on Monday, April 6th 09 at 21:55)
-
PHP - Conditional Statements
In PHP, you can use Conditional Statements to make decisions. Let’s say you wanted to give your customer a discount if he/she has an order over £5 (I know I’m generous!). You can easily do this by using the ‘If’ statement.
Let’s create the IF statement:
<?php
define(’CHOCOLATECAKE’, 3.50);
define(’SWISSROLL’, 1.50);$subtotal = CHOCOLATECAKE + SWISSROLL;
echo “Sub total of your order: £” . $subtotal . “. Thanks for visiting! “;
if( $subtotal >= 5.00 )
{
$totalcost = ($subtotal * 0.90);
$grandtotal = number_format($totalcost,2);
echo “This order qualified for a discount! “;
echo “Your grand total is: £” . $grandtotal;
}
else {
$subtotal = number_format($subtotal,2);
echo “Your grand total for your order is £” . $subtotal;
}
?>
As you may notice I am charging customer’s 3.50 for the cake and 1.50 for the swiss roll. If the customer bought both of these (equalling £5) it would be eligable for discount! The basic princpiple is that if the $subtotal is over the value of 5 then it creates a new variable called $totalcost. The $totalcost is worked out by the $subtotal being multiplied by 0.90 to subtract 10% off the order.
You will also notice there is an ‘Else’ function in there as well. If the ‘If’ function turns false (as in the order is below £5) the ‘Else’ function is performed. The Else funtion in this script will output the $subtotal variable if the order is below £5
The layout of writing an IF statement is as follows: if (your argument here) {commands here}
(Post created on Monday, April 6th 09 at 17:30)
-
PHP - Constants
A constant in PHP stores a value like a variable but if a Constant is given a value it can’t be changed in the script.
To declare a constant you have to set it out in the following way. Let’s say we wanted to give a chocolate cake a fixed price:
define(’CHOCOLATECAKE’, 1.50);
or even a swiss roll! ummm
define(’SWISSROLL’, 1.25);
If you wanted to use a constant all you have to do is use the name of the Constant such as:
echo CHOCOLATECAKE;
or even:
echo SWISSROLL;
Using these Constants will obviously output the price to the browser. You can use these constants to work out the total cost of both by using Variables and Constants together:
$totalcost = CHOCOLATECAKE + SWISSROLL;
The $totalcost now has a value of 2.75 and subsequently this variable is now of the ‘float’ data type as it’s a decimal number. You can see why PHP is a very good language to build customer order forms etc. You now have a variable that has a value and we can now output this to the browser:
echo “Total cost of your order: £” . $totalcost . “. Thanks for visiting!”;
As you can see you can effectively use constants and variables together!
(Post created on Monday, April 6th 09 at 14:15)
-
PHP - Variable Types
In PHP, there are 6 data types:
Some of them everybody may know of already:
String - This data type has quite simply a string of data such as flower231tulip
Integer - This data type holds numbers such as 834
Float - This data type is used for real numbers such as 12.45
Boolean - This data type is used for true or false values
Array - Stores multiple data items
and the Object data type.
If a variable hasn’t got a value the data type is known as ‘NULL‘ to indicate nothing basically!
(Post created on Monday, April 6th 09 at 13:25)
-
PHP Variables
In PHP, variables are used for storing a value, whether it’s a text string or numbers.
A variable in PHP has to start with the ‘$’ sign followed by whatever you want to call the variable and then the variables value which would look something like this:
$dvd = “Casino Royale”
a number can also be stored in a variable:
$ageoffilm = 3
So what would happen if we made a PHP script using these variables?
<?php
$dvd = “Casino Royale”;
$ageoffilm = 3;
?>
<html>
<head><title>Movies</title></head>
<body>
<?php
echo “Best bond film: ” . $dvd . “<br />”;
echo “How old is the film: ” . $ageoffilm . “<br />”;
?>
</body>
</html>
This would output:
Best bond film: Casino Royale
How old is the film: 3By the way you may notice the cotcatination operator which is basically just a period “.”
You can use this operator to add strings together as shown in the example above.
(Post created on Sunday, April 5th 09 at 23:45)
-
PHP - Dynamic Content
Dynamic content in PHP basically means that the content changes. For example: If a visitor to your site submitted a comment you could have your script to output the date and time of the comment back to the user. As the date and time will be different in every comment it’s known as dynamic content. Let’s use the date function:
<?php
echo “<p>Comment processed. Date and time processed: “;
echo date (’H:i, jS F Y’);
echo “</p>”;
?>
The above will output to the browser: Comment processed. Date and time processed: 18:20, 4th April 2009
Quite easy to be honest and PHP can be used in many ways like this!
(Post created on Saturday, April 4th 09 at 18:40)
Calendar
| M | T | W | T | F | S | S |
|---|---|---|---|---|---|---|
| « Jun | ||||||
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 | 31 | ||||
Archives
Recent Articles
- PHP - Rounding Off Numbers
- PHP - Single vs Double Quotation Marks
- PHP - Loading Files Into Your PHP Script By Using require() and include()
- PHP - Replacing Strings With Other Strings
- PHP - Finding Strings Within Strings
- PHP - Using strlen() To Test String Length
- PHP - Using The explode() Function
- PHP - Changing The String Case
- PHP - The nl2br() Function
- PHP - Trimming Strings
Links
Categories
- PHP (22)
- Uncategorized (1)


