Beginner PHP Tutorial

banner_PHP

By Edwin Diaz for Udemy

Looking for more than a guide? Check out Edwin’s full PHP course.

Note: This post is part of our “Getting Started” series of free text tutorials on some of our most popular course topics.

To jump to a specific section, click the table of contents below:

Introduction

A Brief History

Getting Started

Installing the Development Software
Installing a Code Editor

Embedding PHP

Comments

Variables

Numbers

Arrays

Control Structures: Logical Expressions

Functions

Application


Introduction

In this beginner’s guide to PHP, we will cover some of the syntax and foundations of PHP and in the end we will create a small application that will insert data into a database using an HTML form and PHP.

A Brief History

PHP is a server-side scripting language created in 1995 by a gentleman named Rasmus Lerdof. PHP originally stood for Personal Home Page, but it was later changed to PHP: Hypertext Preprocessor. The reason PHP is called a scripting language is because it does not get compiled like programming languages.

A compiler is simply software that converts the regular English words to binary code (zeros and ones) for computers to understand.

Because PHP is so easy to use and at the same time so powerful, several large companies use it on their websites, such as Facebook, Google, and Twitter, just to name a few. The PHP language provides many useful features to make things a lot easier for regular users and developers.

Getting Started

Getting started with PHP is quite easy, since it could be done online and offline. The right way to code with PHP would be to start on your computer and then create your final project online.

Because PHP is a server-side language, we need a server to run it, but to run it on the computer we can use a development software package.

Here is a list of the most commonly used software to run PHP locally:

  • WAMP (Windows)
  • MAMP (MAC OS)
  • XAMMP (Windows and MAC OS)

This development software will allow you to have all the necessary components to run PHP on your computer.

Once any of these software packages are installed, you can start running PHP locally from your computer. So, let’s start coding with in PHP.

Installing the Development Software

Let’s assume you installed XAMPP on your computer. The XAMPP Control Panel will be installed, and this is where you turn on the services needed to run PHP. Below is a screenshot of what the XAMPP control panel looks like in Windows and on a Mac, from top to bottom.

image46
image48

The control panel application can be found inside your XAMPP folder, which was automatically created when XAMPP was installed. In a Windows computer, this folder can be found in your C: drive > XAMPP. If you have a computer with a Mac OS then you will find this folder in your applications > XAMPP.

Windows OS users will list XAMPP under programs and Mac OS users can find it in their Launchpad or applications.
All that is needed to start running PHP is Apache and MySQL, so go into your XAMPP control panel and click start on those services or modules. Once these modules have been started successfully, PHP can run on the computer.

Installing a Code Editor

Once we have our development environment, we need a code editor. If you have a Windows machine you can use Notepad++ or Brackets. If you have a Mac you can install TextWrangler and you can find all these editors just by Googling their names.

image47

On this beginner’s guide the code editor brackets will be used. Above is a picture of how Brackets looks once it is open.
Inside the XAMPP folder there is a folder called htdocs; this is where all the PHP files will be placed. All the files placed in the htdocs folder will be executed by our local server software (XAMPP).
On a Windows system, go to your C: drive and find the XAMPP folder, then navigate to your htdocs folder. Create a shortcut for your htdocs in your desktop so that you can easily access everything inside. The folder htdocs will be the equivalent of the online server folder, www or public_hmtl in most hosting services.

image50

Here is a shortcut in our desktop to the htdocs folder.

image49

Inside your htdocs create a folder called PHP, like the one you see in the picture above.

image47

Open your code editor; in this instance Bracket will be used.

image53

Drag or open your PHP folder into your code editor, and automatically you will see that the working left area of brackets will have just one folder available.

image58

Right-click on the left dark area where it says PHP (the folder we created within brackets) and click on new file.

image56

Name your file hello.php.
Note: If you right-click on the name of the file, you can easily rename it, delete, save and just close it. On the right side (the light area) is where we type our PHP code.

image63

All PHP code needs to be enclosed by PHP tags; in addition, you need to always end the code with a semicolon, which tells PHP to finish and jump to the next command.

image59

Let’s go ahead and create a code that will print out “Hello” in the browser.
In this case we use a predefined function called “echo” for printing out text in the browser that PHP provides out of the box for the programmer to use. To view this code, open your browser and type localhost/php/hello.php. As you can see, the word “Hello” is printed in the browser. Now that we know how to get PHP running and even print text in the browser, let’s take it up a notch.

Embedding PHP

image64 Because PHP was designed to work with HTML, it can be embedded anywhere as long as you use the PHP tags.

Comments

To make comments in PHP, we can use two forward slashes for single line or one forward slash with the asterisk for multi-line comments. As you can see, single-line comments are simply two forward slashes. For multi-line comments we need a forward slash following at a least one asterisk – or you can have more, but to finish the comment, another forward slash is needed at the end.

Variables

In programming, variables are like containers of data that can be referenced by their name. We can assign variables numbers and text, and make the data change according to our programs. We define variables in PHP by placing a dollar sign in front of the name. You can give a variable any name as long as it doesn’t start with a number. Here are some examples:

$Example;
$example_1;
$EXAMPLE_23

Of course, some ways are better than others – for example:

$first_name;

$firstName;

Always be sure to end your commands with the semicolon. The variables we define above are empty, so let’s use them below.

$name = “Edwin”;

In this example, we are defining and assigning a value to the variable. Variables can hold different data types, like string (text) or numbers (integers or floats).

$integer = 23; // This is an integer

$float = 1.5; // This is a float number

$string = “Edwin”; // Text are called strings in PHP and other programming languages.

Create a new file by right-clicking the left dark area in Bracket or just create a new file called variables.php in your code editor if you are using another code editor.

image67

Now, open and close your PHP tags and put some spaces in between them so you can place your PHP code in the middle.

image69

In brackets go to File > Project Settings
If you are using brackets, let’s use a really cool functionality called “live preview”, which will let the user see everything as it is saved.

image71

You will get a pop-up box like this above; just enter the path for your folder, which should be this:
http://localhost/php
You are all set!
Let’s use some variables. If you’re having have issues with it, just type it in your browser, like this: localhost/php/variables.php

image72

In the code above, we declared two variables and concatenated them (put them together) with a dot notation and a string space to separate them. In PHP you use a dot to put text together.

image73

Once the file it saved, click on the lightning symbol, which in your case should be grey, and your browser should you open up with the PHP results.

image74

Numbers

image30

PHP does a good job with numbers, and you can do all kinds of calculations and use many predefined functions to suit your needs.

image32

As you can see, here echo is being used to add two integer numbers and print them on the fly.
Complex math operations are also possible in PHP.

image36

Here we are using parentheses to tell PHP the order of operations it should follow. We use an asterisk for multiplication, so here we first multiply 8 times 5, since it is inside the parentheses, and then we add the results to 5 plus 5, totaling 50.

Numbers

Arrays

Arrays are defined in PHP in two ways:

image38

$list_1 is the shorthand version and $list_2 is the longhand version. The shorthand version uses two square brackets with the values inside separated by commas. On the other hand, in the longhand version the keyword array is used along with parenthesis.
As you can see, arrays are very much like variables. The difference is that arrays hold multiple different data types and even other arrays inside, compared to variables, which can only hold one value.

image40

Here we have a number, a string and another array, which are placed inside the array called $list_multiple.
Let’s play a little with arrays …

image42

You can see the array structure by using a function call print_r() – just place the array name inside of its parentheses, as shown above.

image43

This is what we should get when we use print_r(), but of course if you wanted to print the values, we would do something like this:

image44

image45

In addition, arrays have something called an index. The index is the position of the items inside the array. In order to access individual values from arrays, we need to specify the index. An array’s index starts at zero, so our array code printed out 24 since it is in the zero index in the array, which means the first position.

image12

We can also assign values to an existing index in the array. Here, on line 6 we assign a string or text (CARS) to the index 4 in our $list_multiple array.

image141

This is the output of index 4, even though there is no index 4 originally in our array. When there is no index available, PHP will create one.

Control Structures: Logical Expressions

To test our code with certain conditions with logical expressions, in PHP it is written like this.
if (some condition is true) {
Then execute the code in these brackets
}

image16

In the example above, we are testing to see if the number 1 is smaller than the number 5, and if this is true, we will print, “1 is smaller than 5”.
Starting on line 7, we have another statement “elseif” which checks for another condition. On line 13, we use the last statement “else” like a backup just in case all of our conditions are false.

image18

We can use a variable or array inside the parentheses of this statement, and we can nest conditions like this, as well.
You might be wondering what those triangle (< or > ) looking things inside the parentheses are. These right- and left-angle brackets are called comparison operators, and they are used to compare code.
Control Structures: Loops
Loops syntax is very similar to logical expressions in the sense that we validate a condition and execute it once we find the answer. We have a few different loops in PHP:

  • while loop
  • do while
  • for loop
  • foreach loop

while (condition here) {
Execute code here
}

image19

A file named loops.php was created and, as you can see, there is a while loop inside, but if we save the file and try to view this in the browser, we will be creating an infinite loop.
Here is why: this specific loop inside is saying, As long as $i ,which is equal to 1, is smaller or equal than 5, print “ The number is: “$i”.
The problem is that the variable $i will always be equal to 1 because nothing is being done to change that.
Solution: the loop has to be incremented, like this:

image20

Did you notice the code ($i++) on line 8? This means that every time the loop goes around, it will be incremented by 1. This is the short version of doing this:
$i = $i + 1;
So the second time around, $i will be equal to 2 until it reaches 5, and then it will stop when the condition is met, producing this on the screen:

image21

All the loops validate the conditions and will execute the code until that condition is met. Here is a screenshot with the syntax for all the loops:

Here are the various loops available in PHP. They all do very similar things, but are used in different ways, as you can see.

Functions

Functions in PHP are defined by first using the keyword function and then the name of the function you want, following parenthesis and brackets. This could be anything you want as long as you use the same name convention, as you do with variables.
function name () { PHP CODE HERE } The parentheses are there to pass data into the function, and the square brackets are where the function executes all of the code.

image33

The above file “function.php” was created with the code shown above. If the file is saved as it is, nothing will happen. This is because, in order to call the function into action, the function has to be called by using the name with parentheses, ending with a semicolon.

image36

The code above will call the function say_hello() and it will print out “hello” in the browser.

image32

Once we save the file and view it, you can see that we get the word “hello” printed in the window.

image01

In the example above, we have a function that uses the comparison operator “==” to check if $name is equal to the string “Peter”. Since the condition is not true, it will fall to the else statement.

image02

As you can see, functions are really useful since we can wrap all the code we want and then call it by using the name of the function. The best part is that we can call the function from other files, as well.

Application

Now that you know the basics of PHP, it’s time to build a small application that inserts data into a database.

image03

Let’s get our working environment ready. In your htdocs folder, create another folder called app, and then drag it into brackets or just open it up in your editor.

image04

Then create two files: one named index.php and the other db.php.

image05

In your index.php, place some HTML markup as shown above – we are assuming that you know HTML, so this should be easy for you.
Before writing PHP, let’s go ahead and create a database and a table.

image06

Go to localhost/phpmyadmin in your browser. This will bring up the software installed with XAMPP called phpMyAdmin, which will help you organize databases and tables more efficiently than doing it from the terminal or command line.

image07

On the left side you can see all the databases available in phpMyAdmin.

image08

Click on the databases tab.

image09

Write the database name you want to create, and click on the create button on the right.

image52

You can see our newly created database on the right. Click the name app_test.

image54

Step 1: in the name field, write the name of the table – in this case, users. Then in step 2 write the number of columns for the table – in this case, 3. In step 3, just click save.

image55

After clicking save, you get this screen; you need to input the name of each of the columns for the table users.

image57

Here, the first column was named ID, with type INT for integer, which means only integer data is allowed, with a length of 11 characters long. The ID column will also be the index of the table, and it will also increase incrementally every time we insert information into the user table. For the ID column, you will follow steps 1 through 5.
The username row has a type of VARCHAR, which means Variable Character, and it can hold numbers and letters; the password field is set just like the username.

image60

Once you finish filling out the data, all you have to do is click save in the right-hand bottom corner of that window.

image62

Now our table has been created.

Now everything is set up to for use here in phpMyAdmin. Now let’s go to our app folder and create our PHP code, which will communicate with our database and table.
To connect to our database, a few things are needed:

  • Localhost
  • Username
  • Password
  • Database name

In most cases, the host is always localhost, or the IP address of your server. In this case, it’s localhost.
The default username for MySQL, which is the database being used in this example, is “root”.
The default password is empty, and the database name of course is our database name. Let’s head over to db.php and place this information in some variables.

image65

In reality we can name our variables whatever we want, but in this case, we use descriptive variables.
Now that our database information is ready, let’s use a predefined function that PHP offers to connect to our database, called “mysqli_connect()”.

image66

Here, all the parameters are passed to the function by placing them inside the parentheses and each value is separated by comma.
Now let’s assign a variable to our connection.

image68

Here on line eight, a variable is created and then used to create all the connections for our small application. If our connection does not go through for some reason, we can use the $db variable to check.
Let’s make a condition and check our connection to the database.

image70

Here on line 10, a condition code was created. Because the pre-defined function mysqli_connect will return “true” or “false” we can check it. Now our variable $db has those values.
This if statement is just saying that if $db equals true, then print connected on the browser. Let’s go and check this out by going to localhost/app/db.php in the browser.

image51

Give yourself a high-five, and take a break.
Now that we are connected, let’s go to index.php and make our database connection available there as well, by using another pre-defined function called include().
The function include() will do what the names says: include our db.php code in the index.php, so let’s use it.

image27

As you can see, on line 1, we are opening and closing some PHP tags and in the middle we use the function include() with double quotes wrapping the text or our file name db.php.
Now our connection should be included in index.php, so let’s test it out by going to our localhost/app or just by clicking our lightning symbol in the brackets editor.

image28

If you get “connected” then everything went smoothly; if you don’t get anything, then something went wrong and you need to check your code.
Since we know it’s working, let’s remove the if statement in our db.php

image29

So now the code in your db.php should look like the picture above. Let’s go back to index.php and create an HTML form so that we can send some data to our database.

image31
Here we have a regular HTML form, but we need to modify it in order to send data to our PHP code that will communicate with the database.

image33

In this case, this is how the form looks in the browser using Chrome. Now let’s modify it a little.

image35

Here on the example above, name attributes along with their values were added. Also, the type attribute for the second input was changed from text to password just to hide the text when it’s being typed in that input.
Name attributes will be used to send data to PHP in the form of something called “post super global” and it looks like this $_POST[‘value’] . Post super globals are like variables or arrays that hold POST data coming from an HTML form.
The first input will be used to send the username, and the second the password. How do we know when the data is sent? The data will be sent the minute that submit button is pressed, but we still need to add something else.

image37

In the beginning HTML form tag, another attribute called method with the value of post needs to be included, in order for PHP to recognize the data being sent.

image39

Now your form should look like this, so now the form is ready to send data. Let’s head over to the top of this file and write some PHP.

image41

Here we are using a condition or if statement to check if the data from the input with the attribute name=’submit’ is set. Note that we are also using a predefined function called isset() which checks to see if the value is set.

image25

Here we are catching the data being sent from the HTML from in the post super global $_POST[‘example’]. Note that we are assigning the values from post data coming from the form to new variables on the left.
So whatever the user types in inputs will be saved in these variables – in this case, $username and $password.

Now we are starting to use SQL syntax, which is the language of our MySQL database. In the example above, the highlighted text, which is SQL, is assigned to a variable called $query.

image10

In the INSERT INTO users(), we need to specify the columns of the database table that we will be inserting data to – in our case, username and password.
In the VALUES(), we need to input the data going in from the database – in other words, our variables.
Note that the values in users() don’t have dollar signs; this is because they are just the columns for the table users. Also note that the values in VALUES() have quotes around them; this is because they are text, and remember that all text needs to be surrounded quotes.

image11

Alright, so now let’s use another pre-defined function called mysqli_query() that will send this query string to the database for communication.
Mysqli_query takes two parameters, the connection and the query being sent. So in this case we give it $db for the connection and the variable $query that has the query.
Also notice that the results of mysqli_query() are being assigned to a variable called $send_query in the left; this is for handling the connection later on.
It’s very easy to make a mistake, so let’s make sure that our query is being sent.

image13

Since our query connection now is being held in the $send_query variable, let’s use an if condition to test if the connection is not good. Let’s use a comparison operator called (!) for saying, if $send_query is NOT good, then execute the following.
Here we are using two pre-defined functions to display a problem in the page: function die() with two parameters, a string and the function mysqli_error() which takes the connection as a parameter to display the PHP error.
Let’s type in something in the inputs and click submit to see what happens.

image15

In this example, peter was entered for the username and secret for the password, but you won’t see the password, since we are using the typed password in the input to hide this text. Let’s look at our table to see if we get any data from this form; go to phpMyAdmin by typing localhost/phpmyadmin in the browser again.

image17

Look at what you have done so far – if you got this far, applaud yourself and take a break.
There are many more cool things that PHP can do and this beginner’s guide is just scratching the surface.
In PHP we have an acronym called CRUD, which stands for Create, Read, Update and Delete. This small application that we created was just using the Create part of the CRUD.
Imagine what you can do, knowing the rest of the CRUD. You would be able to create anything with just a click of a button.
PHP is a great, and relatively easy web programming language, and knowing it will help you succeed in your web development career.