Lesson 13

PHP – array

There’s a type of variable that allows us to store a “group” of elements. For example, if we have a list of football players: Messi, Lewandowski, Ronaldo and Rooney, without an array to store them we would need 4 variables:

We can simplify this if we store all of them in a an array, like this: 

Very nice, right? That way we avoid having to create multiple variables to store multiple elements.

You should be asking yourself how can we get the values inside the elements? Very simple, we put the element position inside [] next to the variable name:

This would print “My favourite player is: Lewandowski”. You must be thinking that in position 1 is Messi and not Lewandowski – but, in almost every computer language the arrays start in 0(zero) position. So, in this case, if we wanted to get Messi we would need to do:

PHP – foreach

To allow us to go through every item inside an array there is a PHP command: foreach

What it does is looping through the array and execute the code inside. Using our previous $players array:

We can use this to improve our layouts:

 

MySQL – Retrieve data

Let’s create a new page (select_students.php) and show the inserted data on it.

We start by including the db_connect.php file. But this time let’s do it a bit differently. Instead of the include command we would be better off using include_once. The difference between them is that the later will not allow for a file which has already been included, to be included again. That is preferable in case of data base connection script.

So, our db_connect.php file would contain our connection:

And then we would include it:

This time we SELECT some columns. Let’s check it in more details, the syntax is as following:

Example:

This kind of SQL commands is called query. After we type the SQL query we need to execute it, we do it by running:

This would return us the students names to the PHP variable $results.

Using a foreach we can loop through all records retrieved and show them:

 

« Lesson 12 Index Lesson 14 »