Php, the basics

PHP: Producing dynamic webpages

As seen in the previous article about dynamic languages Vs HTML,

<?php ?>

encloses a block that contains PHP. It can be written directly in your HMTL code. Please remember from this previous article, a index.html file would now be saved as index.php as it contains PHP blocks inside.
As all programming languages, PHP blocks contain instructions. One instruction is generally written per row and it ends with a semicolon. Such an instruction tells the computer to do a certain action.

Let’s see an example of such an instruction:

<?php echo 'HELLO WORLD'; ?>

As you can see, inside the tags

<?php ?>

there is the instruction echo written followed by a text between quotation marks and a semicolon at the end. What does this all mean? To keep it short, as we will get to the echo instruction later on during this course, this instruction allows you to show a text (in this case HELLO WORLD) on your webpage.

From a technical point of view, once the PHP interpreter has transformed the PHP file into a HTML file, a page containing only HTML is the result. This is the page that will be shown to the actual visitor, such as your client or prospect.

Let’s see what PHP has to offer:

PHP variables

A variable is a data that may take different values over time. What kind of values you may ask? It can temporarily stock information during the charging of the webpage such as the username of a visitor or it can be used for some mathematical calculations for instance.

Let’s take an example: You are creating a website and you would like to create a specific customer area. As you will hopefully have more than one customer, you will need to set up once (!) a specific customer registration form that allows all customers to register. One of the fields in this form might be the name of the customer. Defining this one as a variable in your form allows you to generate a form for all customers, each one having his/her own name. 🙂 In order to define the name as variable in the form you have to put a $ in front of name, thus $name.

A variable can not only be a character string like name, but also a number for instance. There are multiple types of variables, such as for instance:

  • string (character string)
  • integer (whole number)
  • bool (boolean which means binary logic – true or false)
  • float (real number)

How does this look like in PHP? Please see the example below:

<?php $user='superuser'; $age=40; $houseowner=true; $housesizesqm=120.5; ?>

As you can see, all instructions are within the tag

<?php ?>

and each one ends with a “;”. In this example we now just defined the variables $user, $age, $houseowner and $housesizesqm.
A variable always consists of two elements: its name, like user or age, and its value, like superuser and 40 from our example above.

And what about mathematics? It’s very easy, PHP is working purely logical:

<?php $number = 3; $result = ($number - 1) * $number; echo $result; ?>

The shown result is 6.

PHP instruction: array

Imagine, you may want to put several values within a variable. How can we do so? Let’s give it a try and create a country table including different variables such as $France, $USA, etc. This could be done the following way:

<?php $countries=array('France','USA','China','India','Canada','Russia','Brazil'); ?>

The instruction array allows you to put several values within a variable. This is all set in a table form. You can now display these values with the echo instruction by indicating the position of the variable within the table. This position is called “index” and it starts at “0”. This means if you want to display the variable $China, then the echo is

<?php echo $countries[2]; ?>

But stop, what is an echo instruction you may ask? Let’s have a look at the following paragraph.

PHP instruction: echo

As briefly introduced in the previous article about dynamic languages Vs HTML echo is the command line to show content.

<?php echo 'HELLO WORLD'; ?>

You would now see HELLO WORLD written on the webpage.

Let’s check our previous example:

<?php
	echo'

Hello '.$user.'

';
?>

The echo line says Hello to the registered user by indicating its registered user name after the word “Hello”, thus “Hello superuser” in our case. This can be useful when you want to customize your website for each one of your clients in order to create loyalty and customer retention for instance.

Please note the syntax in this example: the strings are delimited by ‘ ‘ this way ‘a string’, and the variable is linked to a string with ‘.’:

'string'.variable

So in our example the string ‘ ‘

PHP if statement

It may happen that you want to show specific messages to different groups of users on your website. This brings us to introduce a condition using the if statement. How does it work? You first write the instruction if, then in brackets you add the condition itself and you state then between braces what the instruction is in case the condition is true. Let’s take an example by adding an if statement to pour previous case under the echo instruction:

<?php
	echo'

Hello '.$user.'
	if ($houseowner==true){
		echo 'You are a house owner.

';
	}
	else{
		echo 'You don\'t own a house. // the backslash indicates that the following character is an apostrophe and not the ending of a string

';
	}
?>

After the echo command showing the greeting,


indicates to go to the next line and deal with the if statement. To keep it simple, the command tells you that if the user is a house owner, “You are a house owner” will be displayed, otherwise “You don’t own a house” will be shown. As you can see in order to compare a value, one uses

"=="

in PHP. This is one of the assignment operators of PHP. To keep it short, there are many others, such as

"!="

for unequal or

"<="

for smaller or equal to.

The if statements allow you to show specific information to a specific target audience such as country specific promotions on your website for instance.

<?php
echo'

Hello '.$user.'
if ($country==Brazil){
echo 'Just for you: Today\'s special promotion

';
}
else{
echo 'Nice to see you back here

';
}
?>

There might be a moment, for instance when you’re having a forum and you want to display a certain number of messages, where one instruction (“show username 1 and its publishing date, show username 2 and its publishing date etc.”) would need to be repeated several times. In order to avoid such a manipulation, one can use the instruction while which allows to write once the instruction for all related messages. The while instruction repeats the instruction several times until the condition is fulfilled. As soon as the condition isn’t true anymore, the “loop” stops.
Let’s see its structure:

<?php while ($loop == true) { // instruction within the loop } ?>

Could be useful, right? 🙂

Something else that could be useful at certain times: For this, let’s just quickly get back to the echo as this can be very helpful in case of debugging your website for instance. Here is an example:

<?php echo 'World' ?>

You put the echo above at the beginning of your page where there is an error. If the word “World” appears, then this means your problem is further down on the page. Thus you put your echo further down until the word “World” doesn’t appear anymore. This means your problem is just before the echo and you now know where the problem is in the code. Of course, you can replace the word “World” with another one. 😉

PHP instruction: function

Let’s continue with another PHP instruction: function. A function is a serie of instructions which takes specific actions and gives a value as output. It is like an intelligent tool that adapts to your needs and that can be automated for many basic tasks. You can do many things with functions, such as collecting information, sending a document to the server, search and change variables, send emails, get current daytime, password crypting etc. . These functions are one of the strengths of PHP. Yeah, they are very practical and many of them are ready to use within PHP. And if not, you can create your own function. Amazing, isn’t it?!

Assuming, you want to highlight your different target markets by using a color code. All leads coming from France should be highlighted in blue, those coming from the USA in red and the rest of the World in the standard setting black. One would of course need to define the variable $country first, as seen above. We’ll skip this here and go directly to the function instruction.

Here is what we’re looking for:

<?php
function colorcode($country){
if($country==France){
echo'<font color='blue'>'.$country.'</font>';
}
elseif($country==USA){
echo'<font color='red'>'.$country.'</font>';
}
else{
echo $country;
}
}
?>

What does the code above mean? If the country is France then show the result in blue and you’re done. If this is not the case, then check if the country is USA. If the country is USA, then show the result in red and you’re done. If this is not the case, then show the result in the standard setting black and you’re done. Just for information, in case you’re having many “elseif” you can use the switch instruction instead to simplify the code. However, this goes beyond the first basics of PHP programming and will not be covered within this course.

Instead, let’s look at one of the most used functions of PHP which is including pages. You can easily include a page or a part of a page within another one. This will help you to facilitate tasks like changing your menu. Instead of changing the HTML/CSS of the menu on each page, you can write the menu.php once and all changes within this file will be applied to all pages concerned.

<?php include('menu.php'); ?> //This instruction tells the computer to include the content of the page menu.php here. Same for footer.php further down.

Just for information, “//” is the sign for a comment in PHP.

So let’s see a practical example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Our website</title>
</head>
<body> 
<?php include('menu.php'); ?>

<h1>Our website</h1>



Welcome to our website!



Let’s get started to explore our survival guides

<?php include('footer.php'); ?>
</body>
</html>

This saves a lot of time and energy, and allow you to be more efficient and customer oriented. What else can help to increase your performance? Let’s have a look at HTML forms using PHP.

How to handle HTML forms using PHP?

Forms are very useful to create interaction with your website visitors. Imagine, you have a beautiful form on your website where clients fill in information, but you don’t know how to use this form as HTML does nothing with the entered information? That’s were PHP comes in handy. It helps websites getting intelligent.

To keep it simple, there are two methods of sending data of a form: GET and POST. With GET the data are transferred via the URL (limited number of characters) and one can get them via the array $_GET. With POST you can send as many data as you want and they are transferred via the array $_POST. Most of the time, the array $_POST is used, like in our example below.

In order to get all the information from the user as in the previous example with $user, $age, $houseowner and $housesizesqm, we could have asked this information by letting the user fill out a form on the website, setting up the following code (to simplify, we just ask for user name here):

<form name="registration" method="post" action="login.php">
Please enter your user name: <input type="text" name="user"/> 
<input type="submit" name="submit" value="OK"/>
</form>

This one will now be implemented in the document login.php in order to collect the data from all users. Here’s what this may look like:

<html>
<head><title>Login page</title></head>
<body>

<h1>Welcome to our community</h1>


<h2>Please sign up</h2>


<form name="registration" method="post" action="login.php">
Please enter your user name: <input type="text" name="user"/> 
<input type="submit" name="submit" value="OK"/>
</form>

</body>
</html>

Let’s now create another document called output.php to display the entered data.

<html>
<head><title>Login page</title>
<body>

<h1>Bonjour !</h1>



How are you today, <?php echo $_POST['user']; ?>?

</body>
</html>

As mentioned above, this can be very useful when you want to create a customer area on your website. But how is all this information stored on a database (a system that stores information, remember?! 😉 )?

How do PHP and databases work together?

Referring to our former courses about databases, one communicates with a database, such as MySQL with a special language called SQL. PHP is the interface between you and MySQL. There are several ways to access a database, such as via a command line, a PHP request or the previously seen phpMyAdmin. In order for PHP and a database to work together, PHP first needs to connect to the database, as in the following example:

<?php $servername = 'localhost'; $username = 'user'; $password = 'password'; $dbname = 'DB'; // Create connection $connection = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die('Connection failed: ' . mysqli_connect_error()); } //Fetch data with SQL query $sql = 'SELECT name,color FROM Members'; $result = mysqli_query($connection, $sql); if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo 'Hello, ' . $row['name'] . '.' . ' Your favorite color is: '.$row['color'] .'.';
}
} else {
echo 'Who are you?';
}
mysqli_close($connection);
?>

Don’t be afraid, it just looks impressive. The objective here is not that you understand each single line, it’s just to give you a basic impression on what a SQL query can look like when PHP and databases are working together.

To keep it simple, when a user is registered in the database, the output in our example could be: “Hello, Frank. Your favorite color is: red.” If there is no Frank registered in the database, then it would ask “Who are you?”. Not so complicated, is it?! 🙂

Of course there are a lot of other possibilities with PHP. However, we’ll end this article here, as it should just give you a slight overview of what’s possible with PHP.