UndeadDragon
Super Moderator
- Reaction score
- 448
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 protected]&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 "[email protected]"
$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 = "[email protected]";
$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.