Tutorial An Introduction to PHP

UndeadDragon

Super Moderator
Staff member

An introduction to PHP

What is PHP?
PHP (PHP: Hypertext Pre-processor) is a server-side scripting language, which executes before the server returns the HTML. (PHP cannot be viewed by looking in the source). PHP files can be saved as: “.php, .php3, .php4, .php5 or .phtml”. An important feature in PHP is its ability to connect with many different databases.

How can I get PHP?
PHP is a free, open source software, which can be downloaded here and it requires a server, the most popular is Apache, which can be downloaded here. Most web hosts support PHP, so if you have an account they provide a method to test your scripts without having to install PHP.

Get started with PHP
All PHP scripts are enclosed by either the <?php ... ?> tags or the shorthand tags, which are <? ... ?>. PHP scripts are often contained within the HTML tags, so the syntax would be like:

PHP:
<html>
<head>
<title>A PHP Test</title>
</head>

<body>
<?php
echo("Ahoy World!");
//A simple PHP script
?>
</body>
</html>
The echo(“Ahoy World!”); part of the PHP script simply displays the text “Ahoy World”. All PHP functions must end with a semi-colon (;). The text after // is ignored, as that is a single line comment. Comments which span multiple lines are enclosed by /* and */.

PHP Variables
Variables are an important part of PHP. They are used to store information (or arrays of information). All variables in PHP must begin with the dollar sign ($). If anyone is moving from JavaScript to PHP, they should know that in PHP a variable does not have to be declared before its use, as it is automatically declared when in use. There are a few rules for naming variables:
1. A variable name must start with a letter or underscore.
2. A variable name may only contain letters or numbers.
3. A variable name cannot contain spaces.

Some examples:

PHP:
<?php
$string = "Test"; //Valid
$_string = "Test"; //Valid
$1string = "Test"; //Invalid
$a string = "Test"; //Invalid
$a_string = "Test"; //Valid
?>
Variables can be displayed in an echo() function by either directly displaying it:

PHP:
<?php
$string = "Ahoy World";
echo($string);
?>
...Or by using a concatenation operator. A concatenation operator (.) basically joins 2 strings together. You can use this to join multiple variables together, or to join a variable and some static text. Example:

PHP:
<?php
$string = "Ahoy World";
echo($string . "2");
?>
Variables can also be in arrays and they can be referred to by their index. There are two ways to create arrays. The most commonly used way is to assign each value manually:

PHP:
<?php
$array[0] = 0;
$array[1] = 1;
?>
The other way is to declare all array values in one function:
PHP:
<?php
$array = array(0,1); //Does exactly the same as the first example
?>
You can retrieve the number of elements in an array using the function count($arrayName). Example:

PHP:
<?php
$int[1] = 1;
$int[2] = 2;
$int[3] = 3;
$count = count($int);
echo($count); //Prints 3
?>
If...Else
If...Else is an important feature in all languages. The syntax is as follows:

If (condition)
{
//This code is ran if the condition is equal to true.
}

The condition must have a comparison operator to be able to work. The operators are as follows:

== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

An example of an “if/else” statement:

PHP:
<?php
$year = date(Y); //Gets the year
if ($year == 2000)
   {
   echo("Happy Millennium!");
   }
else
   {
   echo("It is year... " . $year);
   }
?>
While loop
The while loop runs a piece of code whilst a condition is true. The conditions in the while loop use the same comparison operators as if/else. The following example uses the while loop to display the numbers 1 to 100.

PHP:
<?php
$i = 1;
while($i <= 100)
{
echo($i);
$i++; //Increment. Increases $i by 1
}
?>
$_GET and $_POST
If you want to get some information from a form then $_GET and $_POST are your best friend. Which one to use? It depends on your form, the method to be exact. If your form’s method is GET, the information from the form will be passed to the page in the “action” through the URL. It will make the URL look something like:

[noparse]http://www.example.com/mail.php?name=George&email=someone@example.com&message=Ahoy[/noparse]

The information could then be retried on the next page by using $_GET. Example:

PHP:
<?php
$name = $_GET['name']; //Gets "George"
$email = $_GET['email']; //Gets "someone@example.com"
$message = $_GET['message']; //Gets "Ahoy"
?>
Because $_GET displays all the submitted information in the URL, it is obviously not the best choice for validating a username and password, so that is where $_POST comes in. $_POST works in exactly the same way, apart from it doesn’t show the information in the URL, so it is much more secure.

Let’s look at a simple contact form as an example:

contactForm.htm
PHP:
<html>
<head>
<title>Contact Form</title>
</head>

<body>
<form method="post" action="mail.php">
Name: <input type="text" name="name"/>
Email: <input type="text" name="email" />
Message: <textarea name="message"></textarea>
</body>
</html>
mail.php
PHP:
<?php
$to = "receiver@example.com";
$subject = "Contact Form";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$headers = "From:" . $name;
mail( $to,$subject,$message,$headers );
?>
Note: To be able to use the mail() function, you must first configure your php.ini, if using a local server. Click here to see how.

Functions
You can create your own functions in PHP which can make it quicker to do certain tasks which would otherwise need lots of code. You create your own function using the syntax:

function funcName(parameters)
{
//Do stuff here
}

The function name may only contain letters, numbers and underscores and may only start with a letter or underscore. The code which should be executed when the function is called is contained within the curly brackets.

Example:

PHP:
<?php
function multiply($number,$multiplier)
{
$result = $number * $multiplier;
return $result;
}
$answer = multiply(10,100);
echo($answer); //prints 1000
?>
Introducing MySQL
There are different databases that PHP also supports, but I am MySQL tends to be the preferred and most widely used database. PHP can execute queries, which allow it to input or retrieve data to/from a database. Before a query is executed, you must connect to the database. Example:

PHP:
<?php
$host = "localhost";
$username = "root";
$password = "abc123";
$database = "users";

mysql_connect($host,$username,$password);
mysql_select_db($database);
?>
Once you have created a connection and selected a database, you can execute some queries on it. Firstly, imagine that we have a database which has this structure:

Code:
Table: characters
id | FirstName | LastName   |
1 | Homer      | Simpson    |
2 | Marge      | Simpson    |
3 | Bart       | Simpson    |
4 | Lisa       | Simpson    |
5 | Maggie     | Simpson    |
Here is an example query on this table, I will explain it after:

PHP:
$query = "SELECT * FROM characters WHERE id='3'";
$result = mysql_query($query);
"SELECT *" means select all results. "FROM characters" means from the table characters "WHERE id='3'" means where the number in column "id" is equal to 3. So, the whole query means:

Select all results from the table "characters" where the row id is equal to 3.

Now, to get the actual data from the rows. The query has found 1 row which matches the query. The row’s data is id:3, FirstName:Bart, LastName: Simpson. To get each piece of data we will use a while loop with a special condition: while($row = mysql_fetch_array($result)). What this does is get all the data from the query (mysql_fetch_array($result)) and assigns it to $row. You can now access the data inside the while loop by using row as an array, where the index is equal t the column name. Example:

PHP:
$host = "localhost";
$username = "root";
$password = "abc123";
$database = "db";

mysql_connect($host,$username,$password);
mysql_select_db($database);

$query = "SELECT * FROM characters WHERE id='3'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
   {
   $first_name = $row['FirstName'];
   $last_name = $row['LastName'];
   }
echo($first_name . last_name); //Prints "Bart Simpson"
Adding MySQL tables using PHP
If you want to add tables without having to run a query directly through MySQL you can do so through PHP. An example function:

PHP:
<?php
$host = "localhost";
$username = "root";
$password = "abc123";
$database = "user_db";

mysql_connect($host,$username,$password);
mysql_select_db($database);

$query = "CREATE TABLE users (
id int,
username varchar(32),
password varchar(32),
email varchar(255) )";
$result = mysql_query($query);
echo("Table Created");
?>
This query will create a table on the "user_db" database which contains the columns: Id, Username, Password and Email. Id has the "int" type, because it will always be an integer and the username, password and email columns have the type varchar(Number in here represents the max length of the string) which means that it holds a string.

If you wish to learn more about SQL and the different queries, you can check out w3school’s SQL tutorial here.

If you wish to know more about PHP functions you can go to php.net/function name. For example: http://php.net/date() will take you to the date() documentation.

Thanks for reading my tutorial. If anyone wants anything added, please ask.
 

ReVolver

Moderator
Staff member
Excellent tutorial, but you must mention in mail.php that you must edit your php.ini in order for it to send mail. the url tags in the $_GET section need to be fixed. You should add a mysql section to show how to add tables into your DB.
 

UndeadDragon

Super Moderator
Staff member
Excellent tutorial, but you must mention in mail.php that you must edit your php.ini in order for it to send mail. the url tags in the $_GET section need to be fixed. You should add a mysql section to show how to add tables into your DB.
Thanks for the feedback. Everything has been added.
 

UndeadDragon

Super Moderator
Staff member
Thanks for the kind comments :)

Anyone notcied any mistakes? I probably have made 1 or 2, I usually do :p
 

UndeadDragon

Super Moderator
Staff member
You might want to mention something about count() and explode()
I will try and mention count() but I don't really see why I would include explode() in a beginners tutorial.
 

UndeadDragon

Super Moderator
Staff member
You might also want to mention how one can look up functions in the PHP manual simply by going to:

php.net/<function-name>
Thanks. Added.
 

Slapshot136

Divide et impera
for some reason the links dont work for me, other then that it looks good, maybe adding some brief description of what some common php uses are though would improve it
 

UndeadDragon

Super Moderator
Staff member
Links should work now. I don't know what the hell Microsoft word did to my URL tags :p
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Staff member
for some reason the links dont work for me, other then that it looks good, maybe adding some brief description of what some common php uses are though would improve it
Common uses? Anything really, the most common is making dynamic content pages though.
 

Blackveiled

Formerly, Ban-Lord
for some reason the links dont work for me, other then that it looks good, maybe adding some brief description of what some common php uses are though would improve it
Using PHP could mean the difference between a crappy and a decent website. If you don't use PHP, you will have to do a lot more work than necessary also, but it also depends what you are doing too.
 

codemonkey

Code monkey not crazy, just proud.
Using PHP could mean the difference between a crappy and a decent website. If you don't use PHP, you will have to do a lot more work than necessary also, but it also depends what you are doing too.
For static sites PHP isn't necessary.
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Staff member
For static sites PHP isn't necessary.
Indeed, however, now a days static sites rarely go far. People want change, new stuff, new things. You have to give people a reason to come back, something static sites don't do.
 

TFlan

I could change this in my User CP.
Indeed, however, now a days static sites rarely go far. People want change, new stuff, new things. You have to give people a reason to come back, something static sites don't do.
Aka, live updates like Facebook's News Feeds. Google has even stated themselves that they need more real-time applications on their site, and that they are falling behind in that category.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Ghan Ghan:
    Chat should show on the sidebar when not logged in now.
  • Ghan Ghan:
    (You'll still need to log in to post messages)
  • Ghan Ghan:
    Test!
  • tom_mai78101 tom_mai78101:
    I must be in a test server.
  • tom_mai78101 tom_mai78101:
    Nice, Twitter tweets embedding now works
  • Wizard Wizard:
    Yup.
  • Ghan Ghan:
    Excellent.
  • Ghan Ghan:
    @tom_mai78101 Hello there.
  • Ghan Ghan:
    Tagging works in the chat too.
  • tom_mai78101 tom_mai78101:
    @Ghan Missed it.
  • Wizard Wizard:
    Still fixing things here and there. Added widgets to the portal, will make it match the ones here on the forum index tomorrow.
  • Ghan Ghan:
    The venerable World Editor Tutorials site has been converted to HTTPS at last.
  • jonas jonas:
    cool
  • jonas jonas:
    and I can even edit my messages, nice
  • seph ir oth seph ir oth:
    GENERAL CHIT CHAT, YOU ARE A BOLD ONE
  • Ghan Ghan:
    Hello there
  • The Helper The Helper:
    this new chatbox is great and the forum software update is great too
    +1
  • The Helper The Helper:
    upgrade has fixed forum registration spam problem
  • tom_mai78101 tom_mai78101:
    Something tells me we might be able to customize the chatbox a bit, considering that there's a gap under every message.
  • Wizard Wizard:
    Going to deploy a fix soon, just had to take some time for myself this weekend.
  • Varine Varine:
    Unbelievable. Time for yourself? How dare you!
  • Wizard Wizard:
    xD
  • tom_mai78101 tom_mai78101:
    Hm, it is now harder to type anything on an Android phone. Pressing Backspace or Enter keys will dismiss the Android keyboard for some reasons.

    Members online

    No members online now.

    Affiliates

    Hive Workshop
    Top