Author Archive Dr.-Ing. Erik Neitzel

ByDr.-Ing. Erik Neitzel
Lesson 10: PHP GET and POST parameters

This lesson shows step-by-step how PHP inter-script GET and POST parameters are to be used in dynamic web pages. Within WordPress, you see that just by editing a post. Look at your browsers URL when your post editor is open. It says “?post=1008&action=edit&lang=en”. The variables “post”, “action” and “lang” are all variables being filled by WordPress according to what you just clicked in the backend. Let us talk about that.

Why script parameters?

Basically, you could use just one script (file) for your entire website project. However, your code will get rather long, maintenance will get harder and errors more difficult to track. So you may want to exclude certain functionality to other script files. However, every PHP script file works on its own. That means, you will need to transfer data from one script to another. You want to parameterize them.

Based on the purpose of the data being transferred and the origin that data is coming from, there are different types of methods to transfer parameters between PHP scripts. Two of the major methods we are going to discuss here are: GET and POST.

PHP script parameters via GET

GET parameters are coming from the URL, that means the web sites link address within the browser’s address line.

This is how a link within any HTML or PHP file looks like which points to a script.php whilst providing it with a GET parameter.

1
<a href="script.php?var_a=abc123">Anchor text</a>

The parameter’s name is “var_a”, which is completely irrelevant, you can name your parameters as you like, as long as you are able to distinguish between them.

If a user clicks the link above, he will get to the target called “script.php”. Within the file script.php, parameters can be obtained as follows:

1
2
3
<?php
     $your_variable_name = $_GET["var_a"];
?>

In this example, we’re trying to get a parameter called “var_a” and store its value in a variable called $your_variable_name. I would recommend naming that variable the same as as the parameter, but that is not necessary. In the example code above, the variable $your_variable_name will carry the value “abc123”, since that is what the link pointed to.

PHP script parameters via POST

POST parameters are most commonly coming from HTML forms as discussed within the HTML basics article.

The following form will send a parameter named “var_b” to a script called script.php as soon as it is submitted.

1
2
3
4
<form action="script.php" method="POST"><input type="text" name="var_b" /><input type="submit" /></form>

The PHP script script.php now has to do the following to obtain parameter var_b:

1
2
3
<?php
     $your_variable_name = $_POST["var_b"];
?>

Of course you can name the variable storing the parameter’s value the same as the parameter again. In the example code above, the variable $your_variable_name will carry the value the user entered in the input text field.

This is all you need to transfer and collect parameter data between two script files using both GET and POST. You can see that what a CMS like WordPress is doing can be richly complex, yet the underlying structure is never complicated. Otherwise the whole system would suffer under its own weight.

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 9: How to use PHP functions

This brief article shows step-by-step how functions and their parameters are to be used in dynamic web pages coded in PHP such as WordPress scripts. Functions become necessary to cluster all kinds of control structure usage, and they are a great way for WordPress themes and plugins to fully utilize the power of content management systems as a whole.

Why use functions?

Very often you will find yourself using the same code over and over again, especially when using string operations or connecting to databases. Normally you would need to copy and paste the same code several times, and as soon as you wanted to change something, you would need to do that as often as you copied the code. Functions can help 🙂

Basic function design

A simple function consists of the following elements:

  1. A name, which you could invent yourself (as long as the function does not already exist)
  2. Optionally a parameter, which can be used to call the function
  3. The content of the function, meaning the code to be executed when the function is called
  4. Optionally a return value, if you want the functions call result to be saved within a variable, for example

All that sounds pretty complicated. Well actually it’s pretty simple.

A simple function example

Let’s look at some examples. Let’s say you want your web application to say hello for as often as you like. But you’re not sure wether you want to rename “hello” to “welcome” at some later point in time. So you will first create a function like this:

1
2
3
4
5
<?php
     function sayHello() {
          echo "Hello";
     }
?>

That function can now be called within your script using just one line:

1
2
3
<?php
     sayHello(); // will result in "Hello"
?>

The text “Hello” will be presented whenever you call your function that way. If you wanted to change the Hello to something else, you’ll just have to do it at one single code line. That would be your first function.

A parameterized function example

Now let’s say you wanted to greet your logged in user by his name. The problem here is that every user has a different name, right? You can solve this using a parameter:

1
2
3
4
5
<?php
     function sayHello($username) {
          echo "Hello ".$username;
     }
?>

The function now has a parameter called “$username”, which is a variable that can be used to greet your user after saying hello. Pretty simple, right? The function has to be called a different way though:

1
2
3
<?php
     sayHello("Mike"); // will result in "Hello Mike"
?>

Of course you would not want to code the name Mike the hard way as presented above. You would just pass the login user name the user entered to that function:

1
2
3
<?php
     sayHello($login_name); // will result in "Hello" and the name the user provided after a successful login
?>

A return value function example

Now let’s say it’s not just about greetings, but about calculation. Let’s assume you often need to calculate the following: $a + $b – $c * 5. You can do this using a function like this:

1
2
3
4
5
6
<?php
     function calculateMe($a, $b, $c) {
          $result = $a + $b - $c * 5;
          return $result;
     }
?>

The function now expects three parameters: $a, $b, $c, will do the calculation you specified and returns the result to you. You can use that function like this:

1
2
3
<?php
     $myResult = calculateMe(1, 2, 3) // the variable "myResult" will carry the value of -12.
?>

Some remarks on functions

Variables you specified within a function are only available within that function — and the other way around. If you want to use a variable which was defined outside the function, use “global $variable_name” within the function. That way you can work with that variable as if it was defined within the function itself.

The other way around, however, needs to be done using the return value as shown in the example above.

These are the basics for working with functions, parameters and return values in PHP. Functions are great. Use them. They will make your life a lot easier 🙂

Functions within WordPress

Of course WordPress is using functions within every single script. Some of those functions can be used specifically within WordPress themes and plugins. For example, you may want to echo the current post title or show a list of all the blog posts within your database. You can get a full reference on those functions here: https://codex.wordpress.org/Function_Reference

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 8: PHP for loops and conditions

This lesson shows step-by-step how to use PHP for loops and conditions within dynamic web pages. Those control structures are hugely important to generate dynamic content. Think about how WordPress is creating a list of all the posts you have in your database. All the HTML code that is needed to show that list is not written by hand, but generated by a PHP loop. To stick with that example, let us talk about loops.

Implementing loops in PHP

Why loops? Whenever we need to either repeat certain operations for a known or unknown amount of times, we are going to need loops. Loops can make it easier to just repeat the same output without having to copy/paste it several times, which makes it easier to maintain the code. The most important reason for loops, however, is when we want to dynamically build output based on certain conditions.

An example is building a table with a known number of columns and an unknown number of rows, whereas rows are to be repeated for as long as a database backend has data sets left for an entity. We will discuss database connectivity at a later time. For now, let’s settle on learning how to use basic loops in general.

WHILE Loops in PHP

A loop often used for different types of conditions is the while loop. To implement it, simple use the word while, with a condition in brackets, and the code to be repeated within the loop’s content area.

1
2
3
4
5
6
7
8
<?php
     $t = "I will never forget the semicolon at the end of a line<br />";
     $i = 0;
     while ($i < 10) {
          echo $t;
          $i++;
     }
?>

Please note that it is essential to count the amount of times your loop went through a cycle. You do that using an incrementation counter, as seen in the code above. If you don’t, your loop will run indefinitely.

DO WHILE Loops in PHP

Another method of using while loops is the do…while approach. It is the same as above, but the loops code will always be executed at least one time, and the condition is checked afterwards.

1
2
3
4
5
6
7
<?php
     $i = 0;
     do {
          echo "There will be text.";
          $i++;
     } while ($i < 10);
?>

FOR Loops in PHP

A different type of loop is the for loop. It needs three terms or expressions:

  1. The initialization term. It will set the initial or start value of your counter variable.
  2. The abort condition. It compares the current counter value with the maximum value.
  3. The loop operation. It increments or decrements the counter value.

The following code shows the right syntax of a for loop:

1
2
3
4
5
6
<?php
     $t = "I will be repeated for some time.<br />"
     for ($i = 0; $i < 10; $++) {
          echo $ti;
     }
?>

A for loop is a pure counting loop and cannot run indefinitely, however you should pay attention to the terms you provide it with.

Conditions in PHP

We spoke about a counter condition for several times. However there are also other conditions which a while loop would accept and even need in some cases. Let’s look at some basic conditions:

If … else

The most rudimentary form of condition is the if…else condition. It separates different cases, its syntax is as follows:

1
2
3
4
5
6
7
<?php
     if ($i < 0) {
          echo "$i is smaller than 0, promised.<br />";
     } else {
          echo "I assure you, $i is currently either 0 or greater than 0.<br />";
     }
?>

Of course you could also put more than one if clause to the chain:

1
2
3
4
5
<?php
     if ($i > 10) { ... }
     else if ($i < 5 ) { ... }
     else { ... }
?>

Please note that “else if” will only be executed if the first condition is wrong. If you want to have another condition checked at all times, do so as follows:

1
2
3
4
5
<?php
     if ($i > 5) { ... }
     if ($i > 10) { ... }
     if ($i > 20) { ... }     
?>

You can also specify more than one condition at the same time using either && (AND) or || (OR):

1
2
3
4
<?php
     if ($i == 5 && $j != 10) { ... }  
     if ($i == 0 || $j == 0) { ... }  
?>

We will cover the comparison operations “==”, “!=” etc. in a second.

Finally, you could also use another if clause within the execution space of another one:

1
2
3
4
5
6
7
8
<?php
     if ($i == 5) {
          if ($j == 10) {
               ...
          } else { ... }
     }  
     else { ... }
?>

That way you can implemented different types of fallback scenarios for each case.

SWITCH … CASE selections

If you have just one variable which you expect to have different known values at times, the easiest way to differentiate between those cases is to switch between those cases:

1
2
3
4
5
6
7
8
9
10
11
<?php
     switch ($name) {
          case "Mike": 
               echo "I am Mike.<br />";
               break;
          case "Annie": 
               echo "I am Annie.<br />";
               break;
          default: 
               echo "We are the rest.";
?>

Comparison operations in PHP

We already used smaller than “<" and greater than ">” operations. However there are way more comparisons possible:

  • $i == 10: equals
  • $i != 10: not equals
  • $i >= 10: greater or equals
  • $i <= 10: smaller or equals
  • $i == 10 && $j == 11: logical AND combination of two conditions
  • $i == 10 || $j == 12: logical OR combination of two conditions

These are all basic operations you will need to implement loops, differentiate between cases and define the conditions you need.

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 7: Learning PHP: programming basics for output, calculation and variables

This lesson shows step-by-step how variables are used to calculate and visualize content within dynamic web pages coded in PHP. This is what WordPress does all day. PHP scripts are used to deal with the complexity of integrating your amazing content into your theme’s layout and deliver all that as HTML to your visitor’s browser. In order to achieve that, lots of dynamic control structures take action, which we will talk about in a second. Let’s clarify some basics first.

What is PHP?

PHP is a script language, standing for Hypertext Pre-Processor. This also describes what it actually does: PHP processes data and generates HTML information output based on that data. Data is processed using loops, functions, parameters and other stuff that we will discuss within the next lessons.

PHP can be embedded within HTML pages, or the other way around: HTML output can be included within PHP code. Either way, the web server has to be able to process PHP. If you want PHP to handle database requests, PHP itself has to have certain modules in place, depending on your database system type.

If you ordered a standard hosting package at a standard web hosting provider, the odds are good that your server can handle both PHP and database processing. To be sure please lookup your package details, maybe you have to upgrade your account.

How to use PHP

Let’s get started on using PHP to process some stuff.

Embedding PHP within HTML or in a separate file

No matter which way of embedding you want to use, you can embed PHP using the following approaches:

1
2
3
4
<? ... ?>
<?php ... ?>
<script language="php"> ... </script>
<% ... %>

The usual way, which we will also use within this tutorial, is the second approach.

Generating text and markup output

If you want PHP to show something, use the echo method:

1
2
3
4
5
6
7
<?php
     echo "Hello world!";
     echo "<table>
                  <tr><td>11</td><td>12</td></tr>
                  <tr><td>21</td><td>22</td></tr>
           </table>";
?>

Introduction to PHP variables

The idea of using a script language is that you want something to be pre-processed — let it be a simple math calculation, a text filter or a dynamically generated table based on database data. You will need variables to do all that. Let’s see what variables are all about.

Every PHP variable starts with a dollar sign, and you can name it as you wish:

1
2
3
4
5
6
<?php
     $text = "I am a text.<br />"; // a string
     $a = 5; // an integer
     echo $text;
     echo $a;
?>

Notice that the double slash opens a PHP comment, a string must have quotes in place, an integer does not. Let’s look at what you can do with integer variables.

Calculations with PHP

Calculating with PHP is as simple as it can be:

1
2
3
4
5
6
7
8
9
<?php
     $a = 10;
     $b = 5;
     $c = $a + $b; // $c will be 15
     $d = $a - $b; // $d will be 5
     $e = $a * $b; // $e will be 50
     $f = $a / $b; // $f will be 2
     $g = $a % $b; // % calculates remainders, $g will be 0 since 10 / 5 = 2 with remainder 0
?>

You can use the remainder calculation to do differentiate between odd and even numbers within a table, for example. We will cover dynamically generated tables shortly.

Implementing counters with PHP

Very often you will also need counters, to count how often a loop was executed, for example. Loops are discussed later on. You can implement counters as follows:

1
2
3
4
5
6
7
<?php
 $i = 0; // initial value of our counter
 $i++; // same as $i = $i + 1, so $i will be 1
 ++$i; // same as $i++, but "echo ++$i" results in "0" and $i is incremented afterwards
 $i--; // same as $i = $i - 1, so $i will be -1 (assuming a start value of 0)
 --$i; // same as $i--, but "echo --$i" results in "0" and $i is decremented afterwards
?>

Using Arrays within PHP

An array can be seen as a locker with different boxes. Every position within an array is a box you can put something into:

1
2
3
4
5
6
7
8
<?php
     $locker[0] = "socks";
     $locker[1] = "shirts";
     $locker[2] = "ties";
     $locker[3] = "pants";
     echo "In box number one are $locker[0] <br />";
     echo "In box number two are $locker[1]";
?>

Please note that an array starts with 0 just as your loop counters should.

Take some time to play around with these PHP basics. The next lesson will be about control structures, and you should have a full understanding of both HTML and PHP basics that we’ve covered so far.

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 6: HTML form elements

This lesson gives an introduction to HTML form elements and how they are used within web pages. WordPress plugins usually help you as a blogger to create such forms by using your mouse, yet we want to understand what is happening there. That way you are able to fix and improve the forms you create.

A simple HTML form

First of all, let’s look at how a form is used in general.

1
2
3
<form action="mailto:user@domain.de" method="POST" enctype="text/plain">
     <!-- Some input and/or button elements -->
</form>

As you can see, the tag in question is called “form” and has two very important attributes: action and method. Action is responsible for what happens when a user clicks the submit button inside your form. In the case shown above the form data is being send via email by the web server.

As we grow our knowledge of server sided scripting using PHP, however, we will see what we can do if the form action contains a target-script.php. Then it will also get clear what the method attribute is all about. For now let’s just keep in mind not to forget those two attributes. The encoding type is simply for, well, style.

Within a form, you may want to have at least one text input field:

1
<input type="text" name="name" value="Your name" />

If your form use case does not require any other sorts of user data but free text inputs, then you are almost finished. Scroll to the end of this article to get your submit button syntax, and you will have your form. If you need some more stuff, just read ahead.

Radio buttons and check boxes

There are cases in which you want to restrict user input to certain pre-defined values. If you want her or him to decide between two or more specific choices, use radio buttons:

1
2
<input type="radio" name="gender" value="m"/>male<br/>
<input type="radio" name="gender" value="w"/>female<br/>

If the user should have the possibility to select more than just one entry at the same time, use check boxes:

1
2
<input type="checkbox" name="skills" value="1"/>Snowboarding<br/>
<input type="checkbox" name="skills" value="2"/>Skiing<br/>

Please note that the user may see “Snowboarding” but the target to which your form gets send to just receives “skills:1”, since the value for a checkbox named skills is 1. This is the same with any other input element. Values being transferred to the form destination can be different from what the user sees.

Dropdown menus

If you have to display a lot of data, while the user still has just one choice, you may not want to flood your form with fifty radio buttons. You can use drop down menus instead:

1
2
3
4
5
6
7
8
9
<select name="state" size="1">
     <option value="0" selected>Please select</option>
     <option value="1">Alabama</option>
     <option value="2">Alaska</option>
     <option value="3">Arizona</option>
     <option value="4">Arkansas</option>
     <option value="5">California</option>
     <!-- and so on -->
</select>

Here it is important to note again, that the user may see some text like “Alabama” but the target script receives value “1”.

Why is this important? This is advanced, but interesting to know if you are a little more experienced: You may have cases in which you build dropdown lists dynamically using PHP based on database content.

That content can also be changed all the time (this is what databases are for). But then you may have entries within your dropdown list that all look alike at worst (think of surnames, for examples). The value, however, will be different, since here you may want to use primary keys, which are always unique. Then, your target script will know the difference between all the entries.

Password and hidden fields

At times you want the user to have some privacy while typing. For that, you can use input type “password”, which results in seeing stars or bubbles instead of the actual text entered:

1
<input type="password" name="entered_user_password"/>

There are also times in which you want to send some other data to your target destination (e.g. a PHP script) which the user shall not have any influence on. Submitting the clients IP address is an example for such a hidden field, which you can use as follows:

1
<input type="hidden" name="sec" value="abc"/>

Buttons

Finally, a form must be able to get sent and to get cleared:

1
2
<button type="submit" value="Submit">Submit</button>
<button type="reset" value="Reset">Reset</button>

Example form

To sum up what we’ve learned so far, you could have a very simple HTML form like this:

1
2
3
4
5
6
<form action="mailto:user@domain.de" method="POST" enctype="text/plain">
     <input type="text" name="name" value="Your name" />
     <input type="radio" name="gender" value="m"/>male<br/>
     <input type="radio" name="gender" value="w"/>female<br/>
     <button type="submit" value="Submit">Submit</button>
</form>

By the way, it is a good idea to structure form input elements using an HTML table inside the form. That way the form looks more straight. This concludes HTML forms within this PHP MySQL tutorial for now.

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 5: HTML Coding Basics

This lesson gives a step-by-step introduction to HTML coding basics. We’re heading towards simple web frontend design using basic HTML elements as it is being generated by WordPress, ready to be transmitted to the visitors browser at a moments notice.

Yet we want to build that understanding up from scratch. To that end, you could still use one of the fancy visual frameworks like Twitter Bootstrap to get you started, which is totally fine, but would require that you already know about the basics of HTML in order to work effectively. This lesson gives a short introduction into basic markup elements and how they are used.

What is HTML?

HTML stands for Hyper Text Markup Language and is a sub type of XML, the Extensible Markup Language. Markup is formed using so called “tags”. So HTML is used to describe websites. With that in mind, let’s look at some basic components.

Basic HTML page structure

The following code represents a minimal HTML page.

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
     <head>
          <title>Tab text</title>
     </head>
     <body>
          Black on white.
     </body>
</html>

Basic HTML elements

There are a lot of HTML tags. Let’s focus on some stuff we really need. I will provide links for additional stuff when appropriate.

Basic content structure

Let’s say you want to use headings and sub headings, like the ones within this very article. You can do so using the following h1, h2, h3, … tags:

1
2
3
4
5
<h1>Big Heading<h1>
<h2>Sub Heading 1<h2>
<h3>Sub Heading 2<h3>
<h4>Sub Heading 3<h4>
<h5>Sub Heading 4<h5>

Now let’s say you want to separate something from the rest of the content you wrote. You can do that using a horizontal line:

1
<hr />

… or using paragraphs:

1
2
<p>Paragraph content</p>
<p>Another paragraph content</p>

… or using line breaks:

1
2
3
Some text<br />
Some other text<br /><br /><br /><br />
Some other text :)

Ordered and unordered lists

If you want to enumerate list items, do that using a ordered list:

1
2
3
4
5
6
7
8
<ol>
      <li>
             A first item
      </li>
      <li>
             A second item
      </li>
</ol>

If you just want those items to be listed with leading dots, you can do it using an unordered list:

1
2
3
4
5
6
7
8
<ul>
      <li>
             A first item
      </li>
      <li>
             A second item
      </li>
</ul>

Simple HTML tables

Let’s assume you have a rather complex content you want to structure. You can do that using HTML tables like this:

1
2
3
4
5
6
7
8
9
<table><tr>
            <td>First row, first column</td>
            <td>First row, second column</td>
      </tr>
      <tr>
            <td>Second row, first column</td>
            <td>Second row, second column</td>
      </tr>
</table>

Images, links and comments

If you wanted to include images within your HTML website, you can use the IMG-Tab like this:

1
<img src="path/to/image/image.png" alt="Description of image" />

To insert links a user can click on, use the A-Tag like this:

1
<a href="https://www.serpbot.org" target="_blank" rel="noopener noreferrer">Anchor text the user can read</a>

The target “_blank” means a new window/tab will open. You could also use “_self” for the page to load within the same window/tab you’re currently surfing in.

Now you often want to include some comments within your page that is not shown to the user directly but serves you as a marker for something left to be done or anything. You can do that like this:

1
<!-- Comment -->

Please be aware, however, that the user can always lookup the HTML source and is thereby able to see your comments. So you may not want to write down anything that is coming to your mind 🙂

If you need other examples on how to use basic HTML tags please visit http://www.w3schools.com/html/

You can experiment on HTML usage by doing some extensive formatting and link creation in your WordPress visual editor, and then switch to “Text” mode. You can then see the post portion of the HTML that is being created by WordPress and then transported to your visitors web browser.

This concludes the HTML basics for now. Please look at the next article for more advanced stuff like HTML forms.

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 3: Database Modelling and Structurization

This lesson shall give some advice on how to start each database project regarding data modeling and a way to think it through, followed by a brief introduction into the usage of data definition, manipulation and queueing statements.

Basic database design process

The first thing you need to make sure is that you know what your application shall be able to do. Having thought about that, you can decide for a data structure.

Try to think of the following:

  • What are the main entities my database is dealing with?
  • What are the relationships between those entities?
  • Do I need additional relationship tables?
  • What are the main attributes of both my entities and my relationships?

You can use an Entity Relationship Modeling tool or just a sheet of paper — it depends on how complex your database is.

Afterwards, decide for a unique primary key for each of your entities, usually an ongoing number or ID, which is what you will find in every WordPress table, for example.

Now it is wise to sort of “emulate” all your database tables and all your attributes including primary keys using an Keynote/Excel file or a sheet of paper. Visualize your tables and fill them with example data. That way you can be sure not to miss something important. When that is done, think about the kind of data your primary key consists of. Is it data you get from a different system, where you can be sure that every new entry has a different key value, or do you want to let it be filled automatically using auto_increment.

Create table statements

Finally, build your final data model using create table SQL statements (DDL) as discussed earlier. WordPress and every one of its plugins will do that for you, and the only way you will ever see that is by pulling a dump of your database. Within that you will see statements like the following:

CREATE TABLE `wp_users` (
  `ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_login` VARCHAR(60),
  `user_pass` VARCHAR(255),
  `user_nicename` VARCHAR(50),
  `user_email` VARCHAR(100),
  `user_url` VARCHAR(100),
  `user_registered` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `user_activation_key` VARCHAR(255),
  `user_status` INT(11) NOT NULL DEFAULT '0',
  `display_name` VARCHAR(250) NOT NULL DEFAULT '',
  PRIMARY KEY (`ID`)
)

What you see here is a table “wp_users” being created with ten columns (attributes): ID, user_login, user_pass, user_nicename, user_email, user_url, user_registered, user_activation_key, user_status and display_name. Afterwards it is defined that column ID is a primary key (whose value can only exist once). That key can then be used by other tables as a reference for the data row in question. In addition, ID cannot be null and it is automatically incremented whenever a new row is created in table wp_users.

You also see bigint(20) and varchar(100), etc. – which are the data types of each attribute and its allowed maximum value size. There are also some additional information which you do not need to concern yourself with at this time. Yet is is important to get a basic understanding on how and why data tables are being defined within a database.

Insert, select, update and delete statements

Let us now say a user shall be added to your WordPress table wp_users by talking directly to the database.

INSERT statements

You will then issue the following insert statement:

INSERT INTO wp_users 
(ID, user_login, user_pass, user_email, user_url, display_name)
VALUES 
(NULL, 'serpbot', 'abc123', 'serpbot@serpbot.org', 'www.serpbot.org', 'SERPBOT')

We tell the database to INSERT something INTO the table “wp_users”, specify the columns which we want to address, followed by its according VALUES.

SELECT statements

If we wanted to see all contents of our user table, we could ask the database like this:

SELECT * FROM wp_users

That would SELECT all (*) data FROM our table “wp_users”, giving us a list of all the rows that are currently inserted – including our newly inserted user “serpbot@serpbot.org”.

UPDATE statements

If we now wanted to update that users password, we would use:

UPDATE wp_users SET user_pass = 'bcd234'

With this SQL statement we instruct the database to UPDATE the table “wp_users” and SET the attribute “user_pass” to “bcd234”.

DELETE statements

Finally, if we wanted to delete that user from the database, we would do it like this:

DELETE FROM wp_users WHERE user_email = 'serpbot@serpbot.org'

We tell the database to DELETE FROM the table “wp_users” WHERE the attribute “user_mail” equals the value “serpbot@serpbot.org”.

Pretty straight forward, right? This is just meant as an introduction, of course. Yet it may serve as a sign not to be afraid of relational databases and SQL statements when doing maintenance on your WordPress installation or building your own plugin or standalone application from scratch.

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 4: VI Editor in Unix

This lesson is meant to give you an alternative to the WordPress Theme Editor and plugins able to manipulate script file contents. The reason for this is simple: if you make a mistake using an editor that is part of the content management system itself, you will have shut yourself out. The only ways to save your installation are to restore your webspace from a backup or to re-edit your files using the operating system’s file editors of your web server.

In case you have a Unix based system running on the server, the odds are great that you can use VI as a remote editor. That way you do not have to transfer any locally created code files to the server. This brief article shows some basic step-by-step command sequences for you to get started with both Unix environments and VI.

Get connected to the web server using either Putty (Windows) or Terminal (OSX) and the SSH access parameters you either received from your hosting provider, your admin or yourself 🙂

Unix file handling commands

First of all you need to know how to create folders, since you probably want to organize the files you are about to create. If you wanted to create a folder within just the folder you’re currently in, use: mkdir folder-name

If you want to remove a directory you previously created, use rmdir folder-name to do so.

After creating a folder you can then switch to that folder using the change directory command “cd”: cd folder-name

You always get the full path of your current directories using the command pwd.

To create a file in the current directory use: touch file-name.php

Sometimes you need to copy existing files to another location. You can do this using the “cp” command: cp ./existing-file.php ./new-file.php, whereas “./” stands for the current folder and can also consist of several subfolders like ./sub1/sub2/sub3/file.php. Be aware, however, that those subfolders have to exist, they will not be created automatically. Use the commands mentioned above to do so.

If you simply want to move a file, use “mv” instead of cp. That way you can also rename files and folders: mv current-name-or-location new-name-or-location

To remove a created or copied file use the “rm” command: rm existing-file.php

If you lost track on the files within the current directory, use the list command like this: ls -la, which shows you details to all files within that folder.

VI file editing commands

Once you created a file within the directory you want, that file will be blank. You may want to fill it with fancy code, probably 🙂

Please go to the directory you created your file in using cd directory and ls -la to be sure that the file you seek is present and touch file.php if it is not.

Then type: vi file.php in order to open that file in an editor called VI.

The VI editor will show an empty editing space, since your file is still empty. Now please type letter [i] on your keyboard, which results in an “insert” label on the bottom left pane of VI. You can then type code, e.g. <?php echo “Hello world”; ?>

As soon as you’re done coding, please hit [ESC] followed by “:w” which results in “123 bytes written” on the bottom pane.

The Escape key gets VI in the command mode where you can use

  • :w to write (save)
  • :u to undo
  • :q to quit VI

Do not forget to type [i] again if you want to continue coding (assuming that you did not leave VI, if you did, just point Unix to VI file.php again).

I hope this brief introduction into Unix file handling and VI editing helps you get started.

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 2: Relational Database Management System Basics

This lesson gives an introduction towards basic relational database management system concepts. It serves theoretical purpose only. You don’t need this in order to build an application. However understanding what your WordPress system is doing “under the hood” can help put other lessons in context.

A relational database system (DBS) consists of the following components:

  • A database management system (DMBS), a software able to serve the ACID concept
  • A database (DB) which carries relational data

What is the ACID concept?

  • Atomicity (all or nothing – there is no state in between a state before and after a desired change)
  • Consistency (data is consistent before and after a change – regardless of how many internal transactions may be necessary for the system to preserve that secure state)
  • Isolation (apparent exclusive access – you application can access the whole database even if another application is doing the same, without disturbing one another)
  • Durability (data is persistently written to its carrier medium at all times)

For the database system to achieve all this, transactions are used. Transactions are a sequence of operations which result in different states of data. Those operations do not change data accessible by other users until a commit is sent to the DBS. Once a commit is done, only changed records can be accessed, no longer the ones before a change was made.

In order to deal with data in terms of a database system we have to distinguish between the following languages, which are part of the overall Structured Query Language (SQL):

  • Data Definition Language (DDL)
  • Data Manipulation Language (DML)
  • Interactive Query Langauge (IQL)

We use DDL when we create tables, DML when we insert, update or delete table data and IQL when we select certain parts of the database.

A transaction commit can be initiated automatically after each SQL operation or manually using the commit command sent to the database. This is useful whenever you want to collectively change certain data bound together by a business case, without letting just portions of it being accessed by users.

A bloggers perspective toward database concepts

For you as a blogger it is important to understand when database actions are performed and which category they belong to:

  • Installing your WordPress installation creates many database tables and fills them with initial data, some of which are derived from your basic installation input (e.g. your blogs name, your admin users email address or your personal password) (DDL).
  • Each WordPress plugin you activate will most likely create new tables in your database (DDL).
  • As soon as you save a post certain database tables (e.g. wp_posts and wp_post_metadata) will be updated (DML).
  • Whenever you log into your blog software, your user data (user name and password) will be checked for a match within a datbase table (e.g. wp_users when using WordPress) (IQL).
  • When a user visits your website, PHP scripts are called which read data out of your database which is used to deliver seemingly static HTML to the visitors web browser (IQL)

The last point already shows why you as both blogger and WordPress administrator will most likely use caching plugins. Those will pre-load all needed database contents and created static HTML to be served to the browser on each request. That way we prevent the whole database requesting (IQL) processes from being being repeated over and over again for each request without actually having new content in the database. Those plugins have to rebuild that static HTML only when you change a posts content.

The next lessons:

ByDr.-Ing. Erik Neitzel
Lesson 11: How to build a website — PHP navigational skeleton step by step

This lesson describes step-by-step how to build a website’s base structure using PHP. It is what WordPress does before sending your website to your user. Remember that the basic function of all content management systems is to separate layout (theme programming) and data (content creation and delivery). Yet a user always sees the website as a whole. That re-integration of layout and content is what we will discuss within the last four lessons.

Let us start by showing you how a basic PHP skeleton structures different elements of your website: your theme files (e.g. your header and footer) and your content and pages file.

If you attempt to follow this course, you should have at least read the following articles first:

  1. HTML coding basics
  2. Learning PHP — output, calculation and variables
  3. PHP control structures — loops and conditions
  4. PHP inter-script GET and POST parameters

However it is even better if you read all previous articles 🙂

Why create a navigational skeletal structure?

There are various parts of your website which always stay the same. Think of your header and your footer for example. For integrity and maintenance reasons we only want to load content that is different from one request to another. All other content will be created once and integrated when needed.

Otherwise you would need to copy/paste your header and footer code for every sub page you are creating. This can result in errors and is hard to maintain since you’ll have to change every single page for just one tiny header detail, for example.

Prerequisites of your base structure

First of all you should think about what pages your website shall consist of, for example:

  • Home
  • About
  • Privacy
  • Contact

If you know that, think about the basic layout of your website, for example:

  • Header
  • Content
  • Footer

You could also think about a sidebar etc., but we will not focus on positioning elements for now. At first we want to clarify the technical background required to build your skeleton.

Technical background of our skeleton

The “request/response switch” we are about to develop will integrate the following PHP capabilities:

  • Include command
  • Array carrying page definitions
  • $_GET inter-script parameter functionality

This article will demonstrate how to use those aspects for your advantage.

Overall base structure

Let’s talk about the base structure of your base structure 🙂

The following code shows header, content and footer areas, each of which include other PHP files.

1
2
3
4
5
6
7
8
<html><?php include "inc-pages.php"; ?>
       <head><title>...</title></head>
       <body>
              <div id="header"><?php include "inc-header.php" ?></div>
              <div id="content"><?php include "inc-content.php" ?></div>
              <div id="footer"><?php include "inc-footer.php" ?></div>
       </body>
</html>

You can save this file as your future index.php. It is carrying both our request/response switch and the actual content files. You may have noticed that there is an additional file called in-pages.php included at the top. We will cover this in a second.

You also see that there are so called DIV-tags with IDs. You can ignore this for now, I just put it there for you to have a mental marker on how to beautify your website later on using Cascading Style Sheets (CSS). However there is no need to talk about colors and border thickness at this point, since we want to learn how that stuff works technically.

So how does it work? 🙂

Static content first: inc-header.php and inc-footer.php

The files inc-header.php and inc-footer.php are directly responsible to deliver desired content. inc-header.php could show an image, inc-footer.php could print your copyright information. I will not go deeper here, since it’s entirely up to you what to include within those files, e.g. login forms.

However it is a good idea to include your menu within inc-header.php. By menu I mean your links pointing to index.php?section=home, for example. We will discuss this shortly.

Defining our dynamic content files: inc-pages.php

To be able to load different kinds of content files, we first need to define which files to load and by which name to call requests upon them. The actual loading process is done within the inc-content.php, which we will cover in a second. The file inc-pages.php is just to define an array which we will call $files[], which shall look like this:

1
2
3
4
5
6
7
<?php
     $files = array();
     $files['home'] = "content-home.php";
     $files['about'] = "content-about.php";
     $files['privacy'] = "content-privacy.php";
     $files['contact'] = "content-contact.php";
?>

You notice that we are defining four positions within that array: home, about, privacy and contact. Those are pages that we discussed earlier as our website content. Each of these positions point to a simple string. That string is carrying a file name, which we will use in a second.

Building a request/response switch: inc-content.php

Now we will make everything work. The following code is your way to respond to various link requests using the $files[] array as reference:

1
2
3
4
5
6
7
8
9
<?php
     if ( isset( $_GET["section"] ) 
          AND
          isset( $files[ $_GET["section"] ] )
     ) { include $files[$_GET["section"]];
     }else {
          include $files[$_GET["home"]];
     }
?>

Let’s talk about what we’re doing right here. First of all inc-content.php asks if a GET parameter is set AND if the value of that GET parameter is defined within the array $files[]. If both is the case, the file belonging to that request is being included.

Example: Your menu (within inc-header.php) carries a link with anchor text “Home” and link target “index.php?section=home”. If the user clicks on “Home”, inc-content.php recognizes a parameter called “section” with value “home”. It further looks up if $files[“home”] exists. Since this is the case, the file “content-home.php” (as defined in inc-pages.php) is included.

If there is either no section parameter set or the value of section is not within the $files[] array, the home page (content-home.php) is loaded.

Conclusion

I am fully aware that there are thousands of other ways to implement such a switch. The advantage of the solution above, however, is that you do not have to touch the actual switching functionality ever. You just include more positions within your $files[] array, and add some more links to your menu.

You can now use this skeleton frame to build a website delivering the content you need. Within the next lessons we will concentrate on database functionality, used to actually fill the content file with the data from your database (e.g. the text of your post in WordPress).

The next lessons: