Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within...

35
By Ryan Stevenson Guidebook #4 – PHP

Transcript of Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within...

Page 1: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

By Ryan Stevenson

Guidebook #4 – PHP

Page 2: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

Table of Contents

1. PHP Basics

2. PHP Functions

3. WordPress Options

4. WordPress Globals & Database Functions

5. A Complete, Practical Example

Page 3: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

PHP Basics

Before you can learn PHP programming, you need to understand the basics of this language.

The beauty of PHP programming is how versatile it is. It can actually be used alongside HTML, CSS or even Javascript programming.

Since PHP can be used along with other website programming languages, the PHP code on your pages must be properly identified so that it will be parsed correctly.

To indicate an area of PHP code, simply enclose the area of code in the appropriate opening and closing tags:

<?php

// Above is an opening PHP tag

/* The PHP code is everything between the tagsAll of the additional text written here is commented, which means that it isn't parsed as PHP code and can be used to write your own notes with your code.*/

// Below is the closing PHP tag

?>

In the example above, I have shown the opening and closing PHP tags.

The opening tag begins with a less than symbol, followed by a question mark and then the letters php: <?php

The closing tag is just a question mark and then a greater than symbol: ?>

Everything between those two tags will be the PHP code, unless you use comments. A code comment is an area where you can write anything you want, and it won't be processed as PHP code or shown on your live website!

I have provided two examples of code commenting above. The first uses two forward slashes: //

When you use two forward slashes to comment code, it only comments that one line of code. If you wanted to have multiple commented lines that way, you would want to have the two forward slashes at the beginning of each line.

Another commenting option allows you to comment multiple lines at a time. To do this, start it with a forward slash followed by a star (asterisk): /*

Page 4: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

You then end the comment with the same thing backwards – a star followed by a forward slash: */

Everything between the two stars is commented, so it won't get processed.

Why is this even important?

#1. It is considered good programming practice to comment your coding, even if nobody will ever see it, because it helps you to remember what your own coding does. This is especially helpful for beginners that may not be able to look at a section of code and immediately know what it does.

#2. Personally, I find it useful for debugging and even building new features. If you have some code that is working correctly and you want to make some changes to it, you can simply duplicate the code and comment out half of it to essentially save the old code. Then, you can modify the duplicated code. If you run into problems and realized that you messed up the code with your changes, it makes it very easy to revert your changes.

Using PHP in WordPressTypically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin called EXEC-PHP, it will allow you to do just that. Other plugins exist that do the same or something similar, but I have found this one to be reliable.

PHP VariablesNow that you know how to indicate code as PHP code, we can proceed to learn some actual programming.

At the heart of all programming is something called a variable. If you aren't familiar with this term, just think of a variable as temporary storage for information in your code. A variable could be a number or even a string (non-numerical text is referred to as a string in programming).

I have created a very basic example for you below that shows how a variable works:

<?php$a = 1;echo $a;?>

In this PHP code, I have created a variable called 'a' and assigned it a value of the number '1'.

Notice the dollar sign before the letter 'a'. That dollar sign indicates that it is a variable and the letter 'a' is the name of the variable. To assign a value, just use the equal symbol, followed by the value for the variable, and then close it with a semicolon.

The second line of PHP code in the example uses a PHP command called echo. Echo simply outputs information to the browser (browser output is then essentially treated as HTML code). So, this PHP

Page 5: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

code would simply show the number 1 in a browser.

Next, I have created another example just like the previous example, except this time I have used text as the variable value:

<?php$a = 'Hello';echo $a;?>

This example will simply output the text Hello to the browser. The key difference between this example and the previous example are the quotes around the variable value of Hello. Quotes are needed for values that are NOT numerical, which is why I used it in the second example but not the first.

Variable ArraysOnce variables are understood, the next step is to learn about arrays. An array is simply a set of variables.

You actually start an array in the same manner as a variable – with a dollar sign and then the name you want to give the array.

The code below shows an example array being created:

<?php$a = array('Hello', 'Hello Again');echo $a[0];echo '<br />'.$a[1];?>

In this example, I have created an array called 'a' this time. The value begins with array and an opening parenthesis. After that are the values for my array. These are entered in the same way that variables are assigned values (use a numerical value without quotes and text values with quotes), except that you split the values of the array with a comma. The array declaration ends with a closing parenthesis and a semicolon.

I have assigned two values to this array – the first is the text Hello and the second is the text Hello Again. Both are enclosed in quotes because they are text values. Numerical values do not need the quotes.

With the next two lines of code, I have echoed the values of the array. This works very similar to my previous examples with variables except that with arrays you have to reference the name of a key in an

Page 6: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

array to get the value.

With this example, my array keys are automatically assigned a numerical name starting with 0 and incrementing one for each new value in the array. Since I have given this array two values, then there are two keys in the array: 0 and 1.

To reference an array key, simply enclose the key name in brackets: []

For this example, I simply add the number between the brackets to reference that key number.

Array keys can also be given text names instead of numerical names.

I have created another example for you below to see how this works:

<?php$a = array('first_key' => 'Hello', 'second_key' => 'Hello Again');echo $a['first_key'];echo '<br />'.$a['second_key'];?>

When I create the array this time, notice that I have provided an extra value before each of the previous values that I had in the array. The first of these extra values is called first_key and it is followed by an equal sign and then a greater than symbol and finally the original value of Hello. All of that is in reference to one value in the array – Hello and first_key is the key name for that value. I have then done the same thing with the second key and value in the array.

Now when I want to reference the values in this array, I use the key name enclosed in quotes. So, to get Hello to output to the browser, I would use echo and then reference the array value with $a['first_key'] (and be sure to end the line with a semicolon).

Semicolon Line ClosingsBy this point, you may have noticed that each line of my PHP code ends in a semicolon. This will almost always be the case – the symbol tells PHP that you've completed that line of code and/or PHP command and to start looking for the next. Think of this like HTML tags that are self-closing.

Next, I will get into more PHP commands, some of which are not self-closing, so they do not require a semicolon. Most of these commands will make use of parenthesis and/or curly brackets to indicate opening and closing instead of depending on a semicolon as a closer.

If, Else StatementsOne of the most essential PHP commands that you will find yourself using all the time is actually a very simple command: IF.

The IF command is used to control what happens in your coding based on variable values.

Page 7: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

The example below demonstrates the IF command:

<?php$a = 1;if ($a == 1){

echo 'The variable 'a' is equal to 1.';}?>

In the example above, there is a variable that is set to a value of '1'.

Next, the IF command is used. Following the IF command, there is an opening parenthesis, more information, and then a closing parenthesis.

The information between the parenthesis is actually a test statement. $a is making reference to the variable. The two equal signs translates into English as “is equal to”. Last, there is the number 1 and a semicolon.

That entire line of code reads as: “IF the variable by the name of 'a' is equal to the number 1”

Next, you'll notice an opening curly bracket followed by a closing curly bracket two more lines down. These brackets are the opening and closing containers for the IF statement. All of the code between the two curly brackets will ONLY be processed when the IF statement is TRUE!

Now I am going to go another step and complicate the IF statement a bit with the ELSE command. When ELSE is combined with an IF statement, you can provide two sets of code – one that is processed when the IF statement is TRUE (like IF works by itself, as demonstrated previously) and then the other that is processed when the IF statement is FALSE.

Here is another example to demonstrate:

<?php$a = 1;if ($a == 1){

echo 'The variable 'a' is equal to 1.';}else{

echo 'The variable 'a' is not equal to 1.';}?>

In this example, I have added the ELSE command to the IF statement. ELSE actually goes

Page 8: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

immediately after the closing curly bracket for the IF statement, and then a new set of curly brackets are used to contain the code for the ELSE statement (which will run when the IF statement is FALSE).

Obviously, using the example code above will only result in the text “The variable 'a' is equal to 1.” being shown. The code for the ELSE statement that says the variable is not equal to 1 would never run because the variable, $a, is set to the value of 1 and doesn't change in this code. However, this example was done to provide the most basic example of an IF, ELSE statement so you can understand the concept before it gets more complicated.

IF, ELSEIF, ELSE StatementsBefore I move on to a quick practical example of using an IF, ELSE statement, I want to show you one more PHP command that can be used with these statements.

The ELSEIF command works as both commands in one and can be used to make more complex IF, ELSE statements.

Here is another example that demonstrates the ELSEIF command:

<?php$a = 1;if ($a == 1){

echo 'The variable 'a' is equal to 1.';}elseif ($a == 2){

echo 'The variable 'a' is equal to 2.';}else{

echo 'The variable 'a' is not equal to 1 or 2!';}?>

This time my IF, ELSE statement actually has a total of three parts to it!

After the closing curly bracket for the IF command, I have used an ELSEIF command this time instead of an ELSE command.

Immediately after the ELSEIF command is a second test statement, which is asking if the variable $a is equal to the number 2.

Then there is another set of curly brackets for the code for the ELSEIF statement, and then I still have used a final ELSE on the end to run a third section of code when both the IF test and the ELSEIF test are FALSE.

FOR StatementsAs I mentioned before, the code from these IF examples will always display the same thing because the value of the variable $a is defined as the number 1 and there is no way for it to change in the code.

Page 9: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

There are actually a lot of different ways that variable values could be changed in your coding, depending on what you want your script to do, but I want to show you at least one of these ways just so you can see these previous examples work.

This time I am going to make use of a new command called FOR. This command is useful when you want to cycle through whole numbers, either one at a time or in specific increments.

I have provided another example below to demonstrate this command:

<?phpfor ($a = 1; $a <= 3; $a++){

if ($a == 1){

echo 'The variable 'a' is equal to 1.<br />';}elseif ($a == 2){

echo 'The variable 'a' is equal to 2.<br />';}else{

echo 'The variable 'a' is not equal to 1 or 2!';}

}?>

This will output the following to the browser:

The variable 'a' is equal to 1.The variable 'a' is equal to 2.The variable 'a' is not equal to 1 or 2!

Instead of declaring the value of $a as the number 1 in the beginning of the code this time, I am using the FOR command.

The FOR command is actually going to be used to repeat some of my code!

Right after the FOR command is a set of opening and closing parenthesis.

Everything between these parenthesis provides information for the FOR command.

Notice the two semicolons between those parenthesis. These are command separators, like I have explained before, so these are splitting the FOR statement into three different parts, which I will explain below.

The first part should look familiar. This is the previous code that I was using for this line in the previous examples, which sets the value of $a to the number 1. This is telling the FOR statement where

Page 10: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

to begin.

The second part is the end point of the FOR statement. Here, I have used the variable $a and the number 3, but I have used a less than symbol and an equal sign here – this means just that (less than or equal to). This is telling the FOR statement to only run while this part of the statement is true.

The third part is the increment for the FOR statement. I have used $a++ here, which is actually the same thing as $a + 1. This means that I want the value of $a to increase by one each time.

Now let me put all of that into English for you – the FOR statement basically says this:

I want the variable $a to start with a value of 1. Then, I want the value of $a to increase by 1 while the value is less than or equal to 3.

Since the FOR statement loops through code depending on the values provided, this means that the FOR statement will loop a total of three times: once when the value of $a is equal to 1, once when $a is equal to 2, and once when $a is equal to 3.

As you can see from the output of all of this code, each part of the IF, ELSEIF, ELSE statement finally gets processed. This is happening one section of code at a time as the FOR statement changes the value of $a from 1 to 2 to 3.

The last thing I need to point out about this example is the additional set of opening and closing curly brackets that has been added. One is right after the closing parenthesis of the FOR statement and the other as at the very bottom of the code. These are the opening and closing curly brackets used with the FOR statement. Everything between those brackets is code that gets processed each time the FOR statement loops, so that code is being run a total of three times here.

Page 11: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

PHP Functions

PHP is actually a very complex programming language, so there is a lot more to it than simple commands that are used in CSS or tag names used in HTML.

Although it would be nearly impossible to completely explain all of the fundamentals of PHP without writing a multi-hundred page book, there is one more basic PHP concept that I need to explain to you: functions.

A PHP function is similar to a command except that it accepts arguments that can change the way it works. Think of an argument like an HTML tag attribute and value – this is similar.

The first thing that you need to understand about PHP functions is that there are some that already exist in the programming language for you to use, but then you can also create your own to use in your code!

If you are ever looking for specific information on how to do something with PHP programming, search here: http://php.net/

That is the official website for the PHP programming language.

I have personally been using this website almost every day for more than a decade!

This is one of the things that a lot of people don't initially understand about programming – you don't have to know how to do everything! The real key to learning how to program is to understand the fundamentals and know where to get quick help to figure out how to do what you want to do.

If you want to do something with your PHP code and don't know how to do it, just search on php.net for a function that will help.

Even once you know how to write PHP code, you can still use the site as a reminder on how to use specific functions. If I had to tell you the exact order of the arguments of every single PHP function that exists, I simply couldn't do it, despite all of my experience with it, but the truth is that I don't need to know all of that because that information is easily available on that website.

If you work your way through programming a script one function at a time by using that website, you will quickly find yourself able to write a wide variety of scripts without having to reference the site.

PRINT_R FunctionMy intention in this training programing is NOT to simply go through a long list of PHP functions for you guys because I want to show you a practical example of using PHP in WordPress so you can actually see a real-life situation of how it can help your websites.

However, I do want to mention one function real quick, just to demonstrate one of the internal PHP functions.

This function DOES NOT actually have a good practical use, at least not for live websites, although I personally find myself using it all the time when writing code to help with debugging (which is the real practical use for it, in my opinion).

Page 12: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

The function I am talking about is called PRINT_R. This function outputs the contents of an array to the browser.

Earlier in this tutorial, you may remember me showing you an example with an array. When I wanted to output the values in the array, I had to reference the values by their key names.

With PRINT_R, I do not need to use the key names – I simply provide the variable name for the array.

Here is an example of this function using the array that I had created in one of the earlier examples for arrays:

<?php//Declaring the array with key names and values$a = array('first_key' => 'Hello', 'second_key' => 'Hello Again');

//Now I output the contents of the array to the browserprint_r($a);?>

This example outputs the following to the browser:

Array(

[first_key] => Hello[second_key] => Hello Again

)

In this example, I first create my array and store it in the variable $a. Then, I use the PRINT_R function to output the contents of the array to the browser.

To use the PRINT_R function, I simply use an opening parenthesis, then the array variable that I want to output, then a closing parenthesis, and finally a closing semicolon.

Create Your Own PHP FunctionsNow that I have shown an internal function, I want to show you how you can create your own PHP functions.

Before I get into that, it is good to know why someone would want to create a PHP function in a script.

If you remember from my CSS lesson I talked about code bloat. The same thing applies to PHP code. You can actually consolidate your code into functions instead of using a piece of code over and over again.

Page 13: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

Going back to my example with the IF, ELSEIF, ELSE statement and the FOR statement, I want to show you how this could be converted into using a function instead.

In that example, I was using an IF, ELSEIF, ELSE statement to test the value of a variable. What if I wanted to use that same testing statement numerous times through a script I was writing? I could simply copy and paste the code from the inside of the FOR statement and reuse it over and over again as needed, but this would create code bloat.

Beyond code bloat, there are a few more good reasons to use functions. First, it will help you stay more organized, but beyond that, it can save you a ton of work. If I ever decided that I needed to make a change to part of my code and that code was reused over and over again throughout my script, I would have to find each use and make changes to each one. As you might be able to imagine, this takes a lot of time and is tedious work that isn't very fun to do!

Creating your own functions helps you avoid all of this. Below I have reworked the FOR statement example using a function instead:

<?phpfunction process_my_value($a){

if ($a == 1){

echo 'The variable 'a' is equal to 1.<br />';}elseif ($a == 2){

echo 'The variable 'a' is equal to 2.<br />';}else{

echo 'The variable 'a' is not equal to 1 or 2!';}

}

for ($a = 1; $a <= 3; $a++){

process_my_value($a);}?>

In the example above, I get the exact same output that I received the first time around, but this time, I have moved the code that evaluates the value of $a and echoes text to a PHP function that I have created!

I start by using the function command.

Next, I provide a custom name for the function I want to create. It is VERY important to ensure that this function isn't already used or else you will get a PHP error saying that the function is already declared.

Page 14: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

One tactic to avoiding duplicate function names is to create your own unique prefix to use for all of the functions you create in a particular script. This way, you can use short or easy to understand names after the prefix and not worry about whether they are already function names (because you have the prefix before them).

After the custom function name, I use an opening and closing parenthesis. Everything between those parenthesis are my function arguments. All you do is provide a variable name that will be used for that argument value in the function.

In this example, I have provided the variable name $a for the function argument. If I had more than one argument, I would just split each with a comma.

I then use curly brackets to enclose the code for my function – everything between them is the code that is only run when the function is called.

After the function is declared, I have my FOR statement that I used before. Instead of a bunch of code inside of it this time, I simply call the function.

To call the function, just use the name of the function and then put the value inside of the parenthesis (and close with a semicolon). It really looks just like the code used to create the function but without the actual function command.

Now each time my FOR statement loops through, it simply passes the value of $a to the function, when then processes it and outputs the appropriate text.

Although the end the result here is the same, the big difference is that I could continue to use that same function over and over again in my script instead of duplicating the code in the function.

Page 15: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

WordPress Options

Everything up until this point applies to PHP coding in general and is not specific to WordPress. With that said, some of the functions that I use from this point on will be specific to WordPress, so these examples will only work correctly inside of a WordPress site!

By itself, PHP is not able to permanently save data that is stored in variables in a script. To accomplish this, you must use a database.

Database usage with PHP could be a completely separate training course all by itself, so my intentions here are to simply show you how you can use databases within WordPress with much less work than it would taking otherwise.

One big part of the ease when using WordPress is the fact that it has built-in security features that will help to protect your website from malicious input. Whenever you accept raw input from a website visitor and try to save that information to a database unaltered, you put your entire site at risk to being hacked. However, if you follow the recommendations of this guide, you won't have to worry about that because it uses WordPress functions that are protected from this type of website attack.

If you remember in the very first training session on cPanel, I showed you how to create a database table. That table could be used to store information using a PHP script. However, before I get into showing you how that works, I want to show you an even easier method to save data with WordPress.

This easy method is using WordPress Options. This is actually a pre-built database table in all WordPress sites that can be easily used with pre-built WordPress PHP functions.

To start, I just want to tell you the 4 basic option functions that are available and what they do:

add_option – Create a new option and value in the database.

get_option – Get the value of an option from the database.

update_option – Update the value of an option in the database.

delete_option – Permanently delete an option and value from the database.

add_optionFirst, let me show you how to create a new option. This is done using the add_option function.

This function requires two arguments: a name and a value.

The option name needs to be a unique name (use the prefix naming procedure here too, like I recommend doing for function names). This name is used to refer to the option – when you create it, get the value, update the value, or completely delete it.

Page 16: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

The value for the option is whatever information you want to save.

With that said, here is an example of this function:

<?php//Declare text (a value) for the variable $my_value$my_value = 'This is the information I want to save.';

//Create a new WordPress option by the name of my_custom_option_name//The value is set to the value of the variable $my_valueadd_option('my_custom_option_name', $my_value);?>

With just two lines of code, I have created information and permanently stored it in a WordPress database.

You should already be familiar with my first line of code – I am declaring a text value for a variable that I have named $my_value.

The second line of code uses the WordPress function, add_option. Note the opening and closing parenthesis following the function name, which is then followed by a semicolon.

Between the parenthesis for the add_option function are the arguments.

The first argument is the custom name of the option. This is the name that I will use in the future to retrieve the value that I have saved. For this tutorial, I will use the custom option name of my_custom_option_name.

The second argument is the value that I want to save for this option name.

Note that I have enclosed the option name in quotes for the first argument and used a variable for the second. Either is a correct way to pass information for an argument – it just depends on where the information is coming from. Typically, you will know the option name but you may not know the value that you are saving because it has come from your website visitor, so this is the way that I have shown it in this example. We will get to a complete working example by this end of this training session.

get_optionNext, I want to show you how to retrieve the saved information for an option you've created. This is done using the get_option WordPress function.

To use get_option, all you need is the option name that you used when you created the option.

Here is an example of this function:

Page 17: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

<?php//Retrieve the value of the custom WordPress option, my_custom_option_name//Store the value in the variable $my_value$my_value = get_option('my_custom_option_name');

//Output the variable value to the browserecho $my_value;?>

In this example, I start by retrieving the value of the option I created before and save it to a variable.

The get_option function only has one argument – the custom option name that was used to create the option I am retrieving.

I have put my_custom_option_name in quotes (the custom option name I used in the previous example), inside of parenthesis for the get_option function (and closed it with a semicolon).

Then, I simply output the value of the $my_value variable to the browser using the echo command. This step isn't necessary but just something I have done to show an example of what you can do with the information and/or how you can view it.

update_optionIf you ever want to change the saved value of a saved option, just use the update_option WordPress function.

This function works identical to the add_option function (except the function name is different obviously – the arguments used are identical).

Here is an example of the update_option function:

<?php//Declare text (a value) for the variable $my_value$my_value = 'This is the new information I want to save.';

//Update our WordPress option by the name of my_custom_option_name//The value is set to the value of the variable $my_valueupdate_option('my_custom_option_name', $my_value);?>

As you can see, the code above is nearly identical to the previous example for add_option, except the function name is different here. I still use the option name as my first argument and the option value as the second argument.

Page 18: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

delete_optionIf you want to permanently delete an option that you created, use the delete_option WordPress function.

This function uses the same argument as the get_option function – just the option name.

This function is NOT to be used to simply clear the value of an option you have saved – this completely removes the option name and value from the WordPress system! If you decide later to use the same option name again, you must create the option again.

The example below shows the delete_option function in use:

<?php//Permanently delete the custom WordPress option, my_custom_option_namedelete_option('my_custom_option_name');?>

With this function, simply provide the option name that you want to delete and it is gone forever!

Page 19: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

WordPress Globals & Database Functions

When you need to store a lot of data, especially when there may be different data stored for each unique user of your website, you will likely find that using WordPress options becomes more complicated than it is worth.

The next step is to understand how to use WordPress database functions, but before I can move on to this, I first need to explain WordPress global variables to you.

Since a lot of information is stored in WordPress about a variety of different things, you can actually access most of it through the WordPress global variables.

For example, on each WordPress post/page, there is a global variable that contains all of the information for that page like the title, meta information, content, and even custom data specific to that page (it's like options for just for pages).

One of the global variables in WordPress is $wpdb. I am going to focus on this one in particular because it is actually what I will use for storing information to the database!

$wpdb (or other global variables) can be made available anywhere within WordPress by simply using the GLOBAL PHP command, followed by the global variable name, and then a semicolon.

An example of this simple code to call this global variable can be seen below:

<?php//Call the WordPress Global Variable, $wpdb, into the local scope so we can use itglobal $wpdb;?>

By using this simple PHP command, we get access to everything WordPress has stored in that global variable.

Before I dive too far into $wpdb, I want to mention a few other WordPress global variables that you may find useful.

If you want to provide different content on your websites based on whether a visitor is a member of your site or not, you can access WordPress global variables to find this out and to get information of the members.

$user_ID – Use an IF statement to test this global variable. If it is 1 or greater, you have a

Page 20: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

logged in member on the page, otherwise it is a guest visitor to your site or someone not logged into their account.

If the visitor to the site is a logged in member, you can also get this information from global variables:

$user_login – Username.$user_email – User email address.$user_url - User's website URL, as entered in their profile.$display_name – The display name for the user, as defined in their profile.

Additional Global Variables in WordPress can be found here:http://codex.wordpress.org/Global_Variables

Now, on to $wpdb!

Unlike the other global variables I just mentioned in the box above, $wpdb is not a simple variable with a saved numerical or text value.

$wpdb is actually a PHP class. This is yet another subject that could be talked about for quite a while, so I am just going to sum this up for you and tell you the important parts that you need to know to use this – think of a PHP class as a collection custom PHP functions, except you can only access them through the class variable.

With that said, $wpdb contains WordPress database functions that save you a ton of work compared with trying to use databases outside of WordPress.

There are a ton of different functions available to use in this class, so I just want to talk about a few of them for you so you can actually make use of this in a practical situation.

Get more info about functions available in this class here:http://codex.wordpress.org/Class_Reference/wpdb

I had mentioned previously that it is important to prevent malicious code from your users from ending up in your database. This is where that becomes important.

Certain functions in this class will automatically protect you from malicious code while some will not.

Instead of showing you the ones that do protect you, I thought it might be better to demonstrate some that do NOT protect you so I can show you how to use them properly.

Before we can use the database functions for WordPress, we need a database table to use. For this purpose, I will revisit something that I showed you in the cPanel training lesson: creating a database table.

Page 21: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

Login to the cPanel for your website and go to phpMyAdmin. If you have more than one database on your hosting account, select the WordPress database for the site you are using.

Have a ton of WordPress databases on your account and don't know which one to pick? Try this...

First, select a database to try. Then, click on the wp_options table in the database. One of the first rows in that table should be for the option_name 'siteurl'. The option value for that row is the domain name for the website that uses this database table. I have shown a picture of this below:

Once you know you are in the right database, you want to create a new table in that database.

When you first click on the database for the site (in the left-hand menu), it will open a page that lists all of the available tables in that database. Below that, you will find an area to create the new table (as pictured below):

For this lesson, I am going to create a new database table by the name of wp_myform, and this table will have 5 columns.

Notice the prefix that I have used for this database table name: wp_

This prefix is already in use with the existing database tables that WordPress created. It is a good habit to continue this naming structure when you create your own tables (just be sure that the name for the table hasn't been used before). Once we start using PHP code to work with this table, you'll see why the prefix is used for the table name.

When you click on the Go button, a new window will open asking for information about the database table.

I have shown a series of two pictures below that shows the information that I am entering to create this table.

Page 22: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

This first picture should be the initial area of the window that you will see:

For the first picture, there are three sections of information to enter: Column, Type and Length/Values. You can see all of the values I have entered for the 5 rows – just duplicate this information for your table.

Next, scroll in that window to the right, so you can see all of the sections of information that are available. We are looking for the sections Index and A_I, which are almost all the way to the right-hand side of that window.

In just the top row, I want to select Primary as the Index and select the checkbox for A_I (as pictured below):

Page 23: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

Once you have duplicated the information you see here, just scroll to the bottom of the window and click the Save button.

Now that we have a database table to work with, we can proceed to the PHP code and using $wpdb.

$wpdb->queryUltimately, this one database function in this class can actually be used for anything you want to do. Other functions help to simplify certain types of database actions, but this function can still do all of them if you know how to use it.

The real difference between using this function and others is that you need to be able to write your own MYSQL code for the database queries. Although this requires a bit of extra work and effort, knowing how to do this will allow you to use PHP and MYSQL even outside of WordPress, if needed.

To start, I want to show you how to put new information into a database table using this function. I have shown how this work in the example below:

<?php$sql = 'INSERT INTO '.$wpdb->prefix.'myform SET myftime = %d, myfname = %s, myfemail = %s, myfcomment = %s';

$data_array = array(time(), 'Ryan Stevenson', '[email protected]', 'Hello – This is the content of my comment.');

$wpdb->query($wpdb->prepare($sql, $data_array));?>

Page 24: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

There are three lines of code that I have used in this example. Each is explained below:

#1. To start, I am creating the MYSQL query and saving it as a text string in the variable $sql.

This MYSQL query begins with a single quote, followed by the MYSQL command INSERT INTO. This command is used to create a new row of data in a table.

Next, I am using another single quote, and then a period to close that text string and add a variable to the string. The variable is $wpdb->prefix, which is a class variable. This is actually adding the string wp_ to my text. Remember this being used for the database table name prefix? To go back to entering normal text for this string, I use another period and then a single quote after the variable.

Now I enter the name of the database table I created but without the prefix – just myform for this example.

Next, I use the MYSQL command SET. This command is used to indicate that I am going to provide the column values for this new row of information.

Now I am going to enter each of the table column names in the database. You may notice that I only used 4 here instead of 5. I actually didn't use the column myfid because that column is an auto incrementing column, which means it counts numbers by itself (I'll get back to this later).

For each column, I simply provide the name, then a space, and then a placeholder for the value that I will save in that column. I then split each of the columns with a comma.

For the placeholders, you may notice that some say %s and some say %d. %s is used for text and %d is used for whole numbers. A third possible placeholder is available, %f, which is used for decimal numbers.

I then end the whole string with another single quote and a semicolon to close it.

#2. For second part, I am defining an array named $data_array.

This array contains all of the information that I want to save in the database. The array should be somewhat familiar to you because it was covered earlier this in lesson.

Notice the order of the information in the array – this should be done in the same order that the column names are listed in the MYSQL code. There are four values in this array and four placeholders in the MYSQL code – each value in the array corresponds to a placeholder in that code.

The first of these values, time(), is actually a PHP function that returns a timestamp of the current date and time. The time is nothing more than a big number, but it can later be used to translate that number into an actual date and time (we'll get to this in this final example for this tutorial).

The remaining three values of this array are simply text strings that I have manually entered using single quotes. These values could also be variables, but for the purpose of this example, I am just entering the text manually that I want to save.

#3. The last part actually uses the $wpdb class to save the information to the database.

Page 25: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

This involves the use of two functions: $wpdb->query and $wpdb->prepare

I already used the $wpdb class once before to get a variable value for $wpdb->prefix, but query and prepare are functions and not variables!

Notice after $wpdb that I have used a hyphen and then a greater than symbol, followed by the name of the class variable/function. That hyphen and greater than symbol are used with PHP classes to access the variables and functions inside of the class.

First I use $wpdb->query and then an opening parenthesis. Instead of just directly providing a MYSQL query here that already has the user input included, I am going to use $wpdb->prepare to ensure that my user input doesn't include malicious code!

After $wpdb->prepare, I use another opening parenthesis to start this function (inside of the $wpdb->query function).

Next, I simply provide the variable with the MYSQL query string, $sql, and the array for my data that I want saved, $data_array (and separate them with a comma).

Finally, I need two closing parenthesis – one to close the $wpdb->prepare function and another to close the $wpdb->query function. Also be sure to close the whole statement with a semicolon.

To sum all of that up for you, first you're writing the MYSQL query that references the database table name and column names with placeholders. Then, you're creating an array that stores the data that will be used to replace those placeholders. Finally, you're using $wpdb functions to process that MYSQL query with the data array. The end result is that this information is permanently saved in the database as a row!

After running the code above and then browsing my database table, you can see the row of information that was created:

Page 26: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

As you can see from the picture above, the myfid value was automatically filled in for me, even though I didn't provide that column name and value in the MYSQL query. This happened because the A_I box was checked for this column when it was created in the database table. The next row that I add to this table will have a myfid value of 2, and so on.

$wpdb->get_rowThe next function that I want to talk about is $wpdb->get_row. This class function is used to retrieve a single row of information that was previously saved in the database.

The important thing to remember about using database and retrieving information is that information can be retrieved in a number of different ways – depending on the information you have stored in your database.

In this example, I am going to retrieve the information from this database using the myfid column value that was automatically created for me. For the previous information that was saved, I know that the myfid was saved as 1, so I can easily retrieve that row by simply knowing that number:

<?php$sql = 'SELECT * FROM '.$wpdb->prefix.'myform WHERE myfid = 1';$row = $wpdb->get_row($sql, ARRAY_A);print_r($row);?>

This will output the following to the browser:

Array

Page 27: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

([myfid] => 1[myftime] => 1374627927[myfname] => Ryan Stevenson[myfemail] => [email protected][myfcomment] => Hello – This is the content of my comment.

)

In this example, I first create the MYSQL query that will retrieve the row of information. This begins with SELECT * FROM. This means that I want to retrieve all (*) all of the columns from the database table.

Next, I provide the database table name with the table name prefix included.

Then I use the MYSQL command WHERE to indicate that I want to specify a test to use to find the information this database. For this example, I want to retrieve the row that has value of 1 for the column myfid, so I simply use myfid = 1.

Once I have the MYSQL query completed, I want to run that query using the $wpdb->get_row class function.

First, notice that I didn't use $wpdb->prepare this time. Why not? Because there is no user input here that might have malicious code. Basically, if you use placeholders in your query, then you should use $wpdb->prepare.

With $wpdb->get_row, I have provided two arguments: the first is the MYSQL query variable that I created before, $sql, and the second is ARRAY_A. This second argument is telling the function that I want the results returned as a named array.

Also notice that I have saved the return from $wpdb->get_row as a variable, $row. This variable will actually be an array that will contain the saved information from the database!

Now, I use the print_r command to output the contents of the array to the browser (just so I can see them). You could also reference each value in the array individually and echo them along with HTML code to create a customized output for this information – I will also be getting to an example of this at the end of this tutorial.

$wpdb->get_resultsWhat if there was more than one row of information in my database that I wanted to return? Even more importantly, what if I didn't know ANY of the information in the database to use to retrieve it? I'm going to show you how to accomplish both of these things here.

First, if I were to revisit the $wpdb->query example that I used to enter new information into my database and run that a second time, I would end up with two rows of data in my database table (as pictured below):

Page 28: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

So, how would I retrieve both of these rows of information, especially if I didn't know any of the information to use in the MYSQL query (like the numbers for the myfid column, for example)?

$wpdb->get_results allows us to retrieve more than one row of information from a database table with a single MYSQL query, and we can use a somewhat different query from the last example to retrieve this information without knowing the myfid values.

This example shows how to accomplish this:

<?php$sql = 'SELECT * FROM '.$wpdb->prefix.'myform ORDER BY myfid DESC';$row = $wpdb->get_results($sql, ARRAY_A);print_r($row);?>

This will output the following to the browser:

Array(

[0] => Array(

[myfid] => 1[myftime] => 1374627927[myfname] => Ryan Stevenson[myfemail] => [email protected][myfcomment] => Hello – This is the content of my comment.

)[1] => Array(

[myfid] => 2[myftime] => 1374628989[myfname] => Ryan Stevenson[myfemail] => [email protected][myfcomment] => Hello – This is the content of my comment.

))

The first thing that I need to point out here is the MYSQL query that I created. This time, instead of using the WHERE command with a column name and value, I simply left that out! The rest of the query is being used to sort the results, so that part isn't even entirely necessary.

For example, just this MYSQL query would retrieve all of the rows in that table:

Page 29: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

$sql = 'SELECT * FROM '.$wpdb->prefix.'myform';

However, I added the MYSQL command ORDER BY to sort the results. I then specify a column to sort by (this column will be sorted based on the values of each row in that column). Finally, I use the MYSQL command DESC to specify the direction to sort the results – this means descending, so I am sorting results using the myfid value starting with the highest value (the most recent row created) and working down to the lowest value. ASC could optionally be used instead of DESC if you want to sort in ascending order.

This sorting applies to both numbers and letters – when using values that have text instead of numbers, they will be sorted alphabetically in the direction you specify.

Next, I execute the MYSQL query using the $wpdb->get_results class function. This receives the same arguments as the $wpdb->get_row function.

I then output the contents of the entire saved array, $row, so you can see the information that gets returned.

If you notice from the array that is output to the browser, there are actually two more arrays inside of the main array! Each of these inner arrays represents one of the rows of information from the database table.

Page 30: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

A Complete, Practical Example

Now that you know how to use the basics of cPanel, HTML, CSS and PHP, you can actually combine all of this information to make a working, practical example to use on your websites.

For this tutorial, this practical example will essentially be a contact form on your website where you will collect the visitors name, email address, and their message/comment.

This example is also going to include an HTML table on the same page that will show all of the previously saved messages that have been entered. Obviously, you would NOT want to use this actual example on a live website because it would share all of that information with your public visitors, but this example should show you how you could use one page to collect the information and a second page to use for yourself to view the information that people have entered.

Here is the complete, working example – just copy and paste this code into a WordPress page/post to try it out (be sure to have EXEC-PHP plugin installed and active on the site):

<?php// This function is used to retrieve the saved messages from the database// The messages are returned as an arrayfunction myf_get_messages(){

// Be sure to bring $wpdb into the local scope of the function to use itglobal $wpdb;

// Setting a temporary variable as a blank string, which will be returned// If no results are found in the database$tmp_string = '';

// Create a MYSQL query to pull the results from the database$sql = 'SELECT * FROM '.$wpdb->prefix.'myform ORDER BY myfid DESC';

// Process the MYSQL query with $wpdb->get_results// Results are saved as the array $rows$rows = $wpdb->get_results($sql, ARRAY_A);

// The PHP command COUNT tells you how many items are in an array// This IF statement is looking to see if there are results foundif (count($rows) > 0){

// This code is only reached when results are found// To start, we will save the variable $tmp_string with some HTML// This HTML will create the table to display the information

Page 31: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

$tmp_string = '<table class="myf-comment-list-table"><thead><tr><th>ID # / Date / Name / Email Address</th><th>Message / Comment</th><th>Delete</th></tr></thead><tfoot><tr><th>ID # / Date / Name / Email Address</th><th>Message</th><th>Delete</th></tr></tfoot><tbody>';

// Now I want to loop through each of the database results that were found// Use the FOREACH command to do so// Since $rows is holding the database results, I use that first with FOREACH// Then I use the word 'as' and finally I specify a new variable name to// store each of result as it is looped through.foreach ($rows as $row){

// $row['myftime'] contains a timestamp of the date/time when this// message was saved. I want to turn this into something I can read.// This is done using the DATE command. I give an argument to that// command to format the timestamp and another to provide the number.$tmptime = date('m/d/Y H:i:s', $row['myftime']);

// Each time this code is processed, $row will contain a different// database result, so I am going to add to the $tmp_string each// time to add this result to the table. Note that I reference each// item as variable in the $row array! I have also used a new PHP// function here – STRIPSLASHES – this removes forward slashes// from text, which may have been added when saving that text in// the database (this happens when you have things like quotes in your text).// Also note that I have added a form here with a Delete button so you// can delete records from this database.$tmp_string .= '<tr><td><strong>ID #:</strong> '.$row['myfid'].'<br />'.

$tmptime.'<br />'.stripslashes($row['myfname']).'<br />'.stripslashes($row['myfemail']).'</td><td>'.stripslashes($row['myfcomment']).'</td><td><form method="post"><input type="hidden" name="myfid" value="'.$row['myfid'].'" /><input type="submit" name="myfdelete" value="Delete" /></form></td></tr>';

}

// After looping through all of the results, I need to add some closing HTML// for my table to the $tmp_string variable.$tmp_string .= '</tbody></table>';

}

// Now I return the value of $tmp_string when this function is called// This value will be blank is no results were found in the databasereturn $tmp_string;

Page 32: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

}

// Call $wpdb in the local scope to use. We did this already for the function,// but functions do not operate in the same local scope as code outside of functions.global $wpdb;

// Next, I am going to set some default values (which will be blank as default)// The first three store the default values to show in the HTML form on the page// These can be set in this PHP code when someone saves the form without completing// all of the information it needs to process (this keeps the information entered in the form// from being lost).$myfname = '';$myfemail = '';$myfcomment = '';

// These two default values are for error and success messages that can be shown on the page.// They are only set in the code when they need to be displayed.$myferror = '';$myfsuccess = '';

// This holds the saved database results table, which will be blank if there are no results$myf_comment_list = '';

// This looks in the global variable array, $_POST, to see if someone has clicked the button// to save a new message to the database.if ($_POST['myfsave'] == 'Save'){

// This IF statement test ensures that the form information is not blank before proceedingif ($_POST['myfname'] != '' && $_POST['myfemail'] != '' && $_POST['myfcomment'] !=

''){

// Now we create the MYSQL query to save the form information$sql = 'INSERT INTO '.$wpdb->prefix.'myform SET myftime = %d, myfname =

%s, myfemail = %s, myfcomment = %s';

// The data array is populated with the POST global array variables$data_array = array(time(), $_POST['myfname'], $_POST['myfemail'],

$_POST['myfcomment']);

// Now we process the MYSQL query with the data array to save to the database$wpdb->query($wpdb->prepare($sql, $data_array));

// This variable gets set to display this success message on the page$myfsuccess = 'Message successfully saved in the database!';

Page 33: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

}else{

// This code only runs when a new message Save button is clicked but all of the// form information is not provided. This sets an error message and also sets// default form values to ensure information already entered is not lost.$myferror = 'Please fill out the entire form before submitting it!';$myfname = stripslashes($_POST['myfname']);$myfemail= stripslashes($_POST['myfemail']);$myfcomment= stripslashes($_POST['myfcomment']);

}

}

// This detects if a delete button has been clickedif ($_POST['myfdelete'] == 'Delete'){

// This checks the hidden form field, myfid// (int) converts the posted value to a whole number, which it should already be// This is used as a security measure to ensure that the value is a realistic value// and not malicious code.$myfid = (int) $_POST['myfid'];

// Now I only proceed if $myfid is greater than 0if ($myfid > 0){

// This creates the MYSQL query to delete this one row of information// from the database. Notice that I used $myfid directly on the end of the query// instead of using a placeholder, like %d. This is done because I have already// verified this user input myself (I know it is a whole number greater than 0).$sql = 'DELETE FROM '.$wpdb->prefix.'myform WHERE myfid = '.$myfid;

// Now I process the MYSQL query using $wpdb->query$wpdb->query($sql);

// And then I set a message for the success variable to be displayed on the page$myfsuccess = 'The message was successfully deleted from the database!';

}

}

Page 34: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

// This calls the function from the beginning of this code to retrieve the saved messages$myf_comment_list = myf_get_messages();

// The rest of the code below is the actual HTML and CSS code for my page, while// everything above is PHP code that is used to process information for this page// I have also used some random PHP code below to help make this page dynamic (it changes// depending on what is happening on the page).

// To start, I am providing the CSS code that will control the design of this page// Everything here should be information that was already covered in the CSS tutorial.?><style type="text/css">.myf-new-comment-box {

padding:10px;background-color:#eeeeee;border:1px solid #666666;margin-bottom:30px;

}.myf-new-comment-box label {

font-size:16px;font-weight:bold;color:#000000;

}.myferror-message {

padding:5px;background-color:#FFE0E0;border:1px solid #B33B3B;margin-top:10px;margin-bottom:10px;font-weight:bold;

}.myfsuccess-message {

padding:5px;background-color:#FCFFE0;border:1px solid #676E2A;margin-top:10px;margin-bottom:10px;font-weight:bold;

}.myf-comment-list-empty {

padding:10px;background-color:#FFE0E0;border:1px solid #B33B3B;font-weight:bold;

}</style>

Page 35: Guidebook #4 – PHP · Using PHP in WordPress Typically, you can't use PHP coding like that within WordPress post/page content. However, if you search for and install a free plugin

<?php// Now I am beginning the HTML code for my page (everything below these comments)// Note how I have also used some PHP code below. In some instances, I have used the PHP// code to determine whether to display additional HTML code or not (for the error or success// messages, for example). I have also used PHP code to echo variables in this HTML code,// which may be used for the error/success messages or to show default values in the form.?><div class="myf-new-comment-box">

<form method="post"><?php if ($myferror != '') { ?>

<div class="myferror-message"><?php echo $myferror; ?></div><?php } ?><label for="myfname">Name</label><input type="text" name="myfname" value="<?php echo $myfname; ?>" size="48" /><br

/><label for="myfemail">Email Address</label><input type="text" name="myfemail" value="<?php echo $myfemail; ?>" size="48" /><br

/><label for="myfcomment">Message / Comments</label><textarea name="myfcomment" rows="5" cols="50"><?php echo $myfcomment; ?

></textarea><br /><input type="submit" name="myfsave" value="Save" /></form>

</div><?php// Everything below here is HTML/PHP code for the success message and the table that// lists the saved messages in the database. I have even used a more complicated IF, ELSE// statement here to change the HTML that is shown on the page depending on whether// saved messages exist in the database or not.?><?php if ($myfsuccess != '') { ?>

<div class="myfsuccess-message"><?php echo $myfsuccess; ?></div><?php } ?><?php if ($myf_comment_list != '') { ?>

<div class="myf-comment-list"><?php echo $myf_comment_list; ?></div><?php }else{ ?>

<div class="myf-comment-list-empty">There are no saved messages / comments in the database.</div>

<?php } ?>