PHP WordPress

PHP with WordPress, MySQL, and Forms

PHP with WordPress is not a common thing. WordPress is designed for developers as much as its designed for designers. So it becomes very interesting diving in to PHP with WordPress, not too terribly complicated after you figure out all the functions WordPress has built in,  though. The key to success, seems to be, having the right set of tools. There is so much available for wordpress, it’s unbelievable.

I’ve run into countless times already in WordPress where I’m unable to perform the PHP Functions or Database Operations that I’d like to on forms that are submitted. I’m going to walk you through one way how this can be done. The example code is going to be real life code that I’m currently working on, and it is unfinished, but it’s functional.

PHP WordPress

Plugins Needed

  • Contact Form 7
  • Advanced CF7 DB
  • Insert PHP Code Snippet

The Vision

In this case, I want to create a debt/ budget management system. This will be a simple system(at first), that assists the user with planning their budget. The user will fill out forms to add income, bills, and additional expenses. The data will be collected in a database, and displayed for the user and calculations will be performed on the data.

The Scope of This Post

This post will cover one of the modules of the system. This post will only explain the income portion including:

  • Installing and configuring plugins
  • The roles of each plugin
  • How the data is stored in the database
  • Adding income
  • Displaying income
  • Limiting display to only what the currently logged in user added
  • Calculating total weekly and monthly income
  • Creating a reusable set of functions

I plan on adding posts in the future to tie things together. For now, we’ll look at the getting started portion.

The Plugins

The plugins you’ll be using are Contact Form 7, Advanced CF7 DB, and Insert PHP Code Snippet. I tried multiple plugins, before landing on these, and none of them worked well in combination like these plugins do. So I wouldn’t recommend straying away from the listed plugins.

Setup of these is self-explanatory, if you’ve never installed plugins before – look for a post about it by me, I just added it to the to do list.

Configuration, may be something that you need assistance with, though.

Contact Form 7 Install

Contact Form 7 configuration starts with simply installing the plugin. Search for it in the WordPress Plugins area, and click , then click . As far as actual configuration, there’s none needed, you simply install this one. We’ll go over form creation, in a minute. This plugin is the one we use to create the actual forms

Advanced CF7 DB also starts with installation. Search for it in WordPress Plugins, and click , then . There is no additional configuration with this either. You do need to know that nothing is available in this plugin, until you submit a form. So you must create a form, then submit a test submission. This plugin adds the submitted forms to the database, Contact Form 7 alone does not do this.

Insert PHP Code Snippet Install

Insert PHP Code Snippet is the exact same procedure. Add new plugin, search for Insert PHP Code Snippet, click , then click . This plugin adds the ability to insert PHP code, that you create, anywhere in a page or post. This is super nice, if you have little functions you’d like to place in specific places. Otherwise using PHP with WordPress is much more manual, and complicated.

Where do we access these plugins?

In the image above, there are 3 options highlighted in yellow. These are the 3 plugins that we just installed. Throughout this tutorial, we pretty much start at the top of the 3 plugins highlighted in the picture, and work our way down. Lets dive right in, with Contact Form 7!

Contact Form 7

Setting up the form will be made as simple as possible here. Unfortunately Contact Form 7 isn’t a drag and drop interface, but this does allow us to copy and paste a form into the editor. Here is the code:

[hidden user-name default:user_login]
<label> Income Name (required)
    [text* income-name] </label>

<label> Take Home  (required)
[number* income-amount] </label>

<label> Note to Self
[text notes] </label>

[submit "Add"]

to a snippet of more short codes. Pretty smart, if you ask me. I’ll only explain 2 of them in some depth, the rest follow the same pattern.

[hidden user-name default:user_login]

What does that do? Let’s take it word for word.

hidden means just that, it’s a hidden field. Hidden fields are hidden from the user, they exist with whatever value you’d like it to hold. You could have it hold a time or time zone value for the person filling it out, so you’re not using server time for example. In this case, we’re having it fill in the currently logged in user’s username. This is what we’ll use to make sure we only display data that this user has entered.

user-name is simply the name that we’re giving the field. This is what it will be named in the database, so it’s a very important part of our code.

default:user_login is a global variable that is handled by WordPress. This is a very simple way of saying:here’s a session id, what is the use id associated with that, and what is the user name associated with that id? K set that as the default value of this field. I prefer the 3 word short code. Imagine all the words I just typed multiplied by PHP and SQL, that’s the beauty of short codes. PHP with WordPress is amazing!

[text* income-name]

I bet you can guess what this one does. Yup, text field. The significance of text* is the asterisk. Marking it with an asterisk sets it as a required field. In this case all of our fields are required, except the hidden one. This is to avoid errors caused by a field that the user cannot see.

[number* income-amount]

The last one we’re looking at before we move on, is the number field. I specify number, so the form will not allow anything but numbers to go in this area. This will avoid any errors in the future with calculations. If somebody decides they want to put a dollar sign, or anything extra, in this area – it would mess up the PHP script, and they would blame you.

Make the form

Before you get sick of me typing, let’s get on to the form! Copy the code above and paste it in the box, just like the following image:

new contact form

After pasting your code in there, click the save button on the bottom left. This will add your first form!

An error?

There will be an error in the mail tab. It’s a very very simple fix, though. Let’s click the mail tab at the top:

mail tab error

The following image is where you’ll find the error, within the mail tab.

additional headers error

Why are we getting this error?

We get the error in Contact Form 7, because we have modified the default template for the form. The [your-email] portion is trying to pull data from a field that doesn’t exist! So we’ll get rid of that issue, by simply putting in our own email.

additional headers fixed

And the error is gone! Let’s click save again, to make sure this error stays gone, and we can move on to the next step

Adding the form to a page

Adding the form is a pretty simple procedure. We’re not even to the point of using any PHP with WordPress yet. WordPress is an incredible creature, and we’ll be simply adding a short code to the page, to generate the form.

So where’s the shortcode?

You may have noticed, after the contact form was saved, that a short code popped up in a purple area on top of the form editor. This is going to be the short code that we will copy and paste to our new page, yours may have a different ID than mine, so don’t copy mine. Here’s where you’ll find it:

contact form short code

Find that code, and copy it for the next step.

Let’s create a new page! This can be done by mousing over the new button, in the top navigation bar of your WordPress site, and clicking page.

new page

If you’re this far into it, you probably already know how to make a new page. I’m just including these images to avoid any confusion, or misinterpretation of what I’m saying. Now that we’re in the create a page area, simply paste the short code in to the page editor area and click Publish. This is what mine looks like:

add form to page

Now that we have published it, let’s preview it, and add our first entry! We will need an entry to work with, before we can have any data displayed in a table. After you input a Income Name, Income Amount, and Notes if you want to add them, click  add. This is what your form should look like:

add weekly income

After you click the add button, you’ll get a message saying thank you, your message has been sent. That’s because this is normally a subscriber form, we’ll learn how to remove this and redirect to a new page in a different post. If you’ve gotten this far, success! You’re super close to being done.

Advanced CF7 DB

Here’s the tough part, Advanced CF7 DB. Database work is terrifying! Not with this addon, though. Seriously, there’s nothing to do. If you want to verify that the entry went in the database, you can do it here. That’s all we have to do with it, it does it’s own thing! Here’s my DB entry, you can check it out to see if it went in, just like I did.

verify database entry

That’s it, for real. Nothing to do. Next!

PHP Code Snippets

K, here we’ll finally add some PHP code to WordPress. Click on XYZ PHP Code, on your left hand navigation. When that loads up, we’ll click add new php code snippet. That will get the ball rolling. We’re going to start with the Table Styling. That will put some color to our table. Here’s what the input looks like:

add php code

You’ll want to copy the exact code, and names that I use. The functionality depends on that. Feel free to ask questions, if you have any. Here’s the code we’ll use, in between each chunk of code, you will click  and go start a new one. This code is released under the 2-Clause BSD license, details can be found here. Here are the blocks of code:

Tracking Name: Table-Style

//Copyright 2018 Your Epic Tech
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

<?php
?>
<style>
.datagrid table { border-collapse: collapse; text-align: left; width: 100%; } .datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; }.datagrid table td, .datagrid table th { padding: 3px 10px; }.datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #0070A8; } .datagrid table thead th:first-child { border: none; }.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }.datagrid table tbody td:first-child { border-left: none; }.datagrid table tbody tr:last-child td { border-bottom: none; }.datagrid table tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .datagrid table tfoot td { padding: 0; font-size: 12px } .datagrid table tfoot td div{ padding: 2px; }.datagrid table tfoot td ul { margin: 0; padding:0; list-style: none; text-align: right; }.datagrid table tfoot  li { display: inline; }.datagrid table tfoot li a { text-decoration: none; display: inline-block;  padding: 2px 8px; margin: 1px;color: #FFFFFF;border: 1px solid #006699;-webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; }.datagrid table tfoot ul.active, .datagrid table tfoot ul a:hover { text-decoration: none;border-color: #006699; color: #FFFFFF; background: none; background-color:#00557F;}div.dhtmlx_window_active, div.dhx_modal_cover_dv { position: fixed !important; }
</style>

Tracking Name: Functions

//Copyright 2018 Your Epic Tech
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

<?php
//****************************************************************************
//***This function gets all id's for things the user submitted with forms.***
//***This function also filters id's that aren't for the table being built.******
//****************************************************************************
	function dbgetdataids($username,$filter){
                global $wpdb;
		$results= $wpdb->get_results ( "SELECT DISTINCT data_id FROM " . $wpdb->prefix . "cf7_vdata_entry WHERE name='user-name' AND value='" .  $username . "'");
$i=0;
foreach ($results as $result) {
$wpdb->get_results ( "SELECT data_id FROM " . $wpdb->prefix . "cf7_vdata_entry WHERE name='" . $filter . "' AND data_id='" . $result->data_id . "'");
if ($wpdb->num_rows == 0){
unset($results[$i]);
}
$i++;
}
return $results;
	}
//****************************************************************************
//***************This function gets individual entries by id.*****************
//****************************************************************************
	function dbgetentry($name,$id){
                global $wpdb;
		$name = $wpdb->get_results ( "SELECT value FROM " . $wpdb->prefix . "cf7_vdata_entry WHERE name='" . $name . "' AND data_id='" .  $id . "'" );
return $name;
	}
	
//****************************************************************************
//***This function builds the 3 column table, with as many rows as exist.**
//****************************************************************************
function buildtable($username,$namevar,$amountvar,$notesvar,$tablelabel1,$tablelabel2,$tableheader1,$tableheader2,$tableheader3){
                $c = true;		
//**Building Columns
	        $dataid = dbgetdataids($username,$amountvar);
		echo "<div class=\"datagrid\"><table><thead><tr><th>" . $tableheader1 . "</th><th>" . $tableheader2 . "</th><th>" . $tableheader3 . "</th></tr></thead>";

//**Building Rows**
foreach ( $dataid as $id )   {
		$name = dbgetentry($namevar,$id->data_id);
		$amount = dbgetentry($amountvar,$id->data_id);
		$notes = dbgetentry($notesvarvar,$id->data_id);

	        if ($c) {echo "<tr class=\"alt\">";} else {echo "<tr>";}
	        echo "<td>";
		echo $name[0]->value;
                echo "</td><td>";
		echo $amount[0]->value;
		$totals = $totals + $amount[0]->value;
	        echo "</td><td>";
		echo $notes[0]->value;
	        echo "</td></tr>";
                $c = !$c; 
}  

	echo "<tfoot><tr><td colspan=\"3\"><div id=\"paging\"><span><ul><li><a>" . $tablelabel1 . "</a></li><li><a>";
        echo $totals;
	echo "</a></li></ul></span></div></td></tr>";
	echo "<tr><td colspan=\"3\"><div id=\"paging\"><span><ul><li><a>" . $tablelabel2 . "</a></li><li><a>";
	$totals = $totals*4;
        echo $totals;
	echo "</a></li></ul></span></div></td></tr></tfoot></table></div>";
}
?>

Tracking Name: Build-Income-Table

//Copyright 2018 Your Epic Tech
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

<?php
	global $current_user;
        get_currentuserinfo();
	$username =  $current_user->user_login;	
        $tablename = "income-name";
	$tablelabel1 = "Weekly Income";
	$tablelabel2 = "Monthly Income";
	$tableamount = "income-amount";
	$tablenotes = "notes";
	$tableheader1 = "Income Name";
	$tableheader2 = "Income Amount";
	$tableheader3 = "Notes";
buildtable($username,$tablename,$tableamount,$tablenotes,$tablelabel1,$tablelabel2,$tableheader1,$tableheader2,$tableheader3);
?>

So you should have 3 PHP code snippets:

  • Table-Style
  • Functions
  • Build-Income-Table

Table-Style just makes the table pretty.

Functions provides a few necessary functions to gather the data, but not too much data, for the table.

Build-Income-Table builds the table, and calls the functions to gather the data and lay it out nicely.

php code snippets

Now what?

Next to each code snippet, you’ll see a short code. That’s what we’ll use to display the table on the page. 3 short codes. They need to go in correct order, Table-Style, Functions, Build-Income-Table.

You’ll want to copy these 3, and we’ll create another new page, as we did earlier! Paste those puppies into the content area, and let’s see what we get.

Success! You just lied to everybody, and told them you make $50,000 per week! I wish! Let me know if you have any ideas, or how you put this to work. I look forward to hearing about it! PHP with WordPress is not too shabby.

while loops

Arduino – While Loop

While there are a few choices for loops to do while coding in Arduino(Puns intended), you will find a lot of different situations to use each of these loops. We took a look at the for loop in this post, and discovered some of the uses for that. Now we’re going to take a look at the while loop, which is a little different, and I’ll explain to you why and when to use this loop.

while loops

What is it?

The while loop is a block of code that is run while the condition between the parenthesis is true. This is useful when you’re waiting for something, or you have to send a serial command somewhere repeatedly until the desired outcome is returned. It will stay in this loop until the pre-determined requirements are met. This is different from the for loop, because the for loop loops through and increments a variable until it hits a certain number. The while loop can also be written to do this, but that’s not what it’s designed to do.

Uses

One of our examples is going to be a listener, we’ll have the while loop wait until it sees that there is serial data available to read, then it will take action on the serial data that is received.

Another example is a temperature monitor. You can have it sit in the while loop and only do a temperature reading until it changes, then when it changes you can have it send a text message, write to a database, or do any other task imaginable(except split atoms, Arduino is not designed to perform that).

Usage

The following is they syntax from Arduino.cc:

while(condition){
  // statement(s)
}

Let’s break that down, it’s a very simple piece of code, right? In the first line we tell the compiler that we’re using a while statement, by stating “while”. Immediately after that we have a set of parenthesis, inside these parenthesis will be the condition that you are testing. If the condition immediately returns false, your code will never be run, otherwise it runs continuously until it returns false.

You can also use “break” to break out of the loop. This would effectively add a second condition to the while loop, if you use it inside an if statement. For example your while loop tests for sensor a to change, and your if statement tests for sensor b to change. When sensor a changes you have it return false to break out of the loop, when sensor b changes you have it return true to break out of the loop(because an if statement only reads the code inside the curly braces if the condition is true).

 

You can run forever loops by doing while(true). This is not recommended, but it can be done. An example of a forever loop is the “loop()” function that Arduino uses to loop the code you write. This is a loop that is always run, unless you use a break somewhere to remove it from the loop. You can get stuck in this loop indefinitely, so it’s not recommended to use forever loops. Just mentioning it today, so you do know that it’s possible, and that it’s also a risk.

Examples

A great example for this loop, is the post I did about serial communication via the serial monitor. The following is the code from that post:

String data;//initialize string variable

void setup() {
 Serial.begin(9600);//initialize serial
}

void loop() {
 while (Serial.available()){//loop while data is available
 Serial.print("You typed: ");
 data = Serial.readString();//read the data
 Serial.println(data);//print the data to serial monitor
 }
}

If you look through this code, you’ll see in the first line we set up a string named data. In the setup function we instantiate serial at 9600 baud rate. In this case the loop will not run until serial data is available, which would mean that something was sent from the serial monitor to the Arduino. To trigger this, you just have to type something in the serial monitor. Then it does the loop until no more serial data is available, and waits until next time it is available. You can learn more about this process in this post.

perfect image

Creating Effective Images for the Web

How long have you been creating images for the web? Have been creating images for quite a while now. I didn’t realize until recently, when I looked at the statistics driven by the images that I have created, I wasn’t creating effective images. Why not? These images that I was creating weren’t tailored for my audience, they were created for me. Images that I have created for myself aren’t going to attract anybody else’s attention. I’m not trying to attract myself to my own site, I am already on my website everyday.

perfect image

Colors

There was a study recently that showed that the color Orange grab users attention better than any other color. This make sense, fire trucks are Orange and they are pretty hard to miss. Think of other Orange objects around you that are placed there to grab your attention, they are everywhere. Orange is a great color for background, or for a bold heading. This should be the color used to direct the reader towards the most important part of your image.

What other colors are very important to include? Blue and green are two very important colors when trying to attract the attention of men. Its color is make men feel at home, like this place was made for them.

What about women?   Pink is probably the best color for women because it is the most feminine color. Purple is also an amazing color for women, Because purple is the color of royalty, And every woman wants to be a princess.

Keep in mind when you are creating your image, how important it is to identify the audience that you are targeting. If you are targeting everybody, then really you are targeting nobody. Another rule to all of these things that I’m telling you today, is please don’t over do it. If you use a ridiculous amount of Orange in an Image, you will probably scaring people away. These colors are used to attract the attention of people, and generally you’re trying to attract them to a specific part of your image. Don’t create an image that attracts negative attention.

Fonts

The fonts that you use are a very important part of your image. I admit, I have only began to touch the Surface of what fonts can do for me. I have recently come to realize how much my fonts can affect what I’m trying to get across to the reader.

Don’t get me wrong though, fonts can also be overdone in a terrible way. There are some very cool looking fonts out there , but that doesn’t mean that they’re always right for the job. Humans are becoming more and more quick when deciding whether or not they like something. If they can’t read your text in less that about half of the second, they are not going to pay any attention to your image at all.

Your main heading should be bold and easy to read. It should also be short and sweet. This makes it very easy for people to comprehend, if they have to read it more than once, they will probably give up. That is another thing About millennials, if they feel that there is a chance that they will fail at something, like reading your text, they will give up immediately. I am a millennial, and I am living proof of this. If your text is terrible, I’m not going to read it, there’s plenty of other things on the internet.

Artistic text can add a good touch to your image, but again do not over do it. You can use artistic text as a subheading or a short description, very short. You do not want your readers to be straining their eyes trying to read this.

Background images

Please think about your topic before choosing a background. Where a picture is worth a 1000 words, a bad picture is worth a 1000 grammatical errors in between each of those words. If you place an image in the background that isn’t related to something that the reader is looking for, they probably won’t be looking at your picture. Dark pictures have the same effect on people’s view of your picture, dark images are an immediate turn-off for most people.

A moderately bright picture, with perfectly offset text/container will grab a user’s attention, and direct them exactly where you want them to go. Your image is the headline for whatever it is that you’re attracting attention to.

Perfection!

Remember your image is never perfect. I spent quite a while trying to come up with the perfect image to represent a post, that is actually about the perfect image. Don’t get carried away with spending amazing amounts of time to make the perfect image, because you’re only going to realize more flaws in your image as the time goes by.

Your turn!

What do you think? Anything I missed? How are you going to use this info on your own images?

Earn Money While You Sleep

Passive Income Ideas

Welcome to my multi-part passive income ideas post. Here you’ll find some ideas for income that powers it’s self, mostly over time. If you combine multiple passive income opportunities, they can equal out to be quite profitable!

So the focus is not to get one super awesome passive income source, but to stack up many small passive income sources, and slowly build them all up.

What is passive income?

Passive income is income that generates it’s self, most of the time. This is not get rich quick, or easy fast money, this is passive income. Passive income is income that is created by you, by things you create, things that people either buy in to or visit and generate revenue from links/ads. These ideas are all very simple, and can be started/maintainted by spending an hour or two a day working on them. Very very simple.

Earn Money While You Sleep

Affiliate Marketing

More info here!

Affiliate marketing is a great place to start, here are a few of the affiliate programs that I participate in:

Making money from these programs is very simple. You choose what affiliate programs you would like to participate in, and distribute links however you’d like to, within their guidelines of course. It’s very popular to use them within your blog, email marketing, social media, or just word of mouth!

Investing

More info here!

I haven’t dug as deep as I’d like to in this, but I got started with Stash Invest. They have a super simple app, and you can invest as low as $5. Stash Invest will even give you a free $5 to start with, if you sign up using this link!

Another one that I recently started digging in to, is Bitcoin. The company I chose was BitBond. They made it very easy to invest in Bitcoin, and I can’t wait to watch my money grow! Check out BitBond today. Bitcoin is booming, and you don’t want to miss your chance.

Advertising

Advertising is a great opportunity to make some money. This doesn’t require you to have a website. There are creative advertising opportunities, such as carvertise. Carvertise allows you to take contracts advertising with your vehicle. They do body wraps on the vehicle, they’ll pay for installation and removal. I haven’t tried it yet, because my vehicle doesn’t have the factory paint job. I will try it with my next vehicle, though!

Blogging

Do what I’m doing right now! It’s simple to blog, anybody can do it. If you can write a sentence, you can write a post. It can be done any time that you have a minute to spare, I’m sitting in the waiting room at the dentist right now, seriously!

The main methods for making money blogging are any of the methods mentioned here! Direct some traffic at your blog, and eventually you’ll be swimming in the dough.

VIPFunnelCloud can get you rolling. They provide excellent service for blogs with your very own personal domain name. A domain name is the start of your brand, and you want to establish that first. Sign up with VIPFunnelCloud or Hosting24 to get started with this. I’ve worked with both of these companies to get you the best deals, on the best service. They are crazy good companies.

Surveys/Shopping Online

I’m sure you’ve heard it a hundred times, surveys! Yay! You’ve probably never done it, though. You can actually make some decent cash doing it though. Why not, you’re just laying in bed on Facebook anyways. Why not make a couple bucks? SwagBucks is one of the leading sources of this, extremely simple, extra income! If you’re sitting there bored on the bus or waiting in line somewhere, do some simple stuff that will earn you bucks! SwagBucks also earns you cash while you’re doing your normal, every day activities online. All you have to do is download SwagBucks with this link to get started.

YouTube

Have you ever heard of YouTube? I doubt you haven’t, unless you live under a rock, a really really big rock. You can make money from posting youtube videos. The average youtube video is only 1 minute long. Being a millennial, I can say that it’s accurate to say that we will not watch a video longer than 1 minute if it’s for entertainment online, normally anyways.

You can post up 1 minute videos pretty quickly, and monetize those videos with adsense. The more views you get, the more money you make!

Write a Book or an eBook

This is one on my bucket list. I’ll be writing a book in the next year or two, I promise. You don’t need much time to write, seriously. If you get random ideas throughout the day, put them in OneNote with Office365. OneNote is amazing, and I use it every single day to organize things for my blog, things for my life, things for work, etc. I’m researching publishers lately, I don’t have any recommendations, but I’ll update this when I find one that I think I should recommend.

Create and Sell Stock Photos

There are many stock photo websites out there, some free, some paid. You can put up free stock photos to get your name out there, and paid ones to make money. It’s a good idea to have a healthy mixture of both free and paid, it keeps the traffic moving.

Create an Online Course

Websites like Pluralsight and uDemy provide amazing support for people trying to create online courses. They provide trained professionals to guide you through the creation process, and simplify every step of the way. I’ve always watched videos on Pluralsight, and I’m excited to become a course creator with them!

Create an App, or Many

Mobile apps are growing extremely rapid. Companies like Appsmoment make it very easy to create cross platform apps without knowing how to code. This is another one I’ll be jumping on soon. There’s so much potential with apps, you can monetize from ads, in app purchases, and affiliate links. I signed up for Appsmoment literally today, and I plan on having an app released soon. You can create one in as little as 10 minutes, that’s crazy cool.

You can make money

Making Money with Affiliate Marketing

Can you actually make decent money from affiliate marketing? If you’re not willing to read the rest of the post, your answer is YES! Affiliate marketing is much different from any other form of income. Other income sources require you to have money in the first place. They also require you to store, ship, or deliver services/products. Take the hands-on away from your income source, and simply refer people to products.

You can make money

What is affiliate marketing?

Affiliate marketing is basically a referral program. It is different from a referral program though, because you don’t normally just receive a flat fee of $5 or something like that. You can earn hundreds, or thousands off of one sale. You need to figure out what it is that you’re trying to promote, though. Multi-level marketing is somewhat similar, through companies like Le-Vel. I participate in multi-level marketing as well, and profit very well from these programs. That’s not what this is though.

Why is this available?

It’s available, because you’re giving them your personal word, not just some ad. You’re writing a blog post, or a social media post, telling people what you personally recommend and why. A word of mouth advertisement is much better than a picture, which actually makes no sense, because a picture is worth a thousand words, right? Word of mouth is worth a thousand pictures, so take that, history!

What’s the catch?

There really is no catch, but you’re on the right post if you want the truth about affiliate marketing. It’s not a get rich quick scheme, it’s not something you set and forget, even though it’s called passive income. Some get rich, some do pretty good, and some fail. How well you do is up to you. Educate yourself. Check out uDemy, you’ll find that they have many awesome options to train you on things like affiliate marketing, or other passive income sources. I personally train on PluralSight, but the common choice seems to be uDemy. I can tell you, I convinced my company to switch to PluralSight, from our previous training program, because of their awesome content.

Where do I get my links out there?

Social Media is a great source of affiliate link views. Find yourself a pretty picture to relate to it, or use one of the affiliate program’s pictures, and make an eye catching post about your affiliate’s product.

Blogging is very simple to get in to, if I’m doing it, you can to. You can get started with VIPFunnelCloud or Hosting24. While these are both great web hosts, I prefer VIPFunnelCloud. You get what you pay for, when it comes to hosting, and I can say for sure that VIPFunnelCloud provides an awesome set of features, included with your hosting at no extra cost. You also get a free domain, if you purchase one of the higher tier plans – and they’re cheap, for unlimited hosting. I use the top tier plan. From there, you can install wordpress with softalicious installer, and it’s magically ready to go. Code-free.

Word of mouth is another great source to get the word out there. Just the other day, I was talking to my co-workers about Keeper Password Manager. They were looking for a solution for all the passwords that they always forget, and Keeper is what I use, plus they have an affiliate program. They were interested, and I said “Great, I’ll send you a text message with the link, because there was a link to get 15% off if you order today.” Simple as that.

Where can I sign up?

Here are some of the Affiliate programs that I take part in:

Other great places can be found by a simple google search. If I’m trying to post about personal development in the area of time management, I search “Time management training affiliate”. And viola, I get an affiliate link. Make sure you keep track of your affiliate links, and usernames/passwords. That is the actual reason I use Keeper Password Manager, they help sort out things like that.

What is your plan?

What are you going to do? Do you need help? Do you have suggestions? Let me know in the comments, and I’ll help you out!

Hello World Tutorial

Sending Serial Data From PC to Arduino

Today we’re going to learn how to talk to the Arduino. We have already established how to listen. Listening is cool and everything, but we all like to be able to talk sometimes too. This can be very useful when learning how to send commands to your Arduino. You can send text, and have the Arduino act based on what you sent. That’s not what we’re doing today, we’re just going to do a simple send from the serial monitor, and have the Arduino tell us what we said. Do I hear an echo?

What is it?

I always like to start with a what is it. What is it to send serial data from the PC to the Arduino? We all know what serial is, it’s a protocol which literally communicates in 0’s and 1’s, or highs and lows – very dang fast. The serial monitor makes it very easy to send things to the Arduino. There’s a send box built right in to it! All you do, is type in what you want to send, click send and it goes. The part we need to figure out is how to receive that data with the Arduino.

Uses

One of the common uses for this, is as a debugging tool. You can create smaller sections of a large program, and test them using this method. If you’re planning on acting based on received data from another device, you could simulate that data by hand in the serial monitor. Then you can see when and how it acts based off of your input.

Another use is for triggering functions. You may use this as your primary method of controlling the Arduino. We’ll get in to an example of that in a later post, in that post we’ll control an led using text.

Usage

This is the syntax from Arduino.cc:

Serial.readString() 

That’s it! Super complicated, huh? No arguments, nothing! This function simply reads the entirety of what you’ve entered, and you can add it to a variable.

Example

Here’s an example of the usage of Serial.readString().

String data;//initialize string variable

void setup() {
 Serial.begin(9600);//initialize serial
}

void loop() {
 while (Serial.available()){//loop while data is available
 Serial.print("You typed: ");
 data = Serial.readString();//read the data
 Serial.println(data);//print the data to serial monitor
 }
}

This code does nothing, until it sees serial data is available on the usb receive pin. It will simply loop and wait for serial data. Once it sees that there is serial data, with Serial.available(), it will parse that data. The next line you see is simple serial.print stating “you typed:”. Followed by data = Serial.readString();, this will assign the data to a string for later use. The final line prints out the data read from the string. Very simple!

Let’s upload, and run it!

Now, we can open the serial monitor, the output will be blank. In the top of the serial monitor, there’s a text box where you can type. Next to it is a send button.

In here, we can type what ever it is that you’d like to send for your test.

Let’s give it a whirl, and click send!

Now we’re well equipped for some serious conversation with our Arduino! Some of us aren’t able to make friends as quickly as others, so you can obviously see how this would be beneficial in the future.

for loops

Arduino – For Loop

Arduino’s language is packed full of goodies that make things quite a bit easier to accomplish. Without loops, we would rewrite code over and over again, and it would be the ugliest code you’ve ever seen.

It takes a while before some people even start using loops, you’re in the right place if that’s you. Using loops will change the way you structure your sketches completely. You’ll find this is a huge time saver. Some times a little effort goes a long way!

for loops

What is it?

A for loop is a loop that runs a set amount of times. It loops until a predetermined condition is met, you set this condition at the beginning of the loop. Once the condition is met, it breaks out of the loop, and continues on with the code.

Most of the time, it’s good practice to keep the loops in a function or an if statement. Doing this avoids slowing down your sketch, by running through the loop every single time your main loop starts over.

Uses

One of my favorite uses, is using for loops to cycle through each value in an array. One example of a for loop that I used recently, was in a weather station. I designed a weather station that had 16 underground sensors. Instead of running a function 16 times, I ran a for loop that counted up to 16, and ran the function to read from each one individually. This took much less code than it would have otherwise.

Usage

This is the syntax from Arduino.cc:

for (initialization; condition; increment) {
 //statement(s);
}

Let’s pick that apart.

You of course state that you’re using the for loop by starting with “for”. The arguments to the for loop can be tricky at first, but they are fairly easy to understand. You start with initialization. I prefer to start with “int i”. You initialize an int here generally, because you’re going to use that int to count with. This is the variable that you’ll use to determine when the loop is done.

The condition that you’re setting here is what needs to be true for this loop to be done. You could put i<=10 and it will run until it is equal to 10.

The last portion here is increment. Normally I’d simply put i++ here. This is where you’ll add to the int that was defined.

An important note: If you use this to count things in an array, arrays start with an index of 0. So if you programmatically have your sketch determining the length of an array, you need to make sure you’re calling array[i-1]. This would start your index at 0, and make sure you don’t go over the amount of values that’s in the array.

Example

This example will count to 10, waiting 1 second in between each number. You can speed this up by changing the delay at the end of the loop:

void setup() {
Serial.begin(9600); //Initialize serial output
}

void loop() {
Serial.println("For loop starting");

for (int i=0; i <= 10; i++) { //initialize the for loop, it will count i up to 10, then be done
 Serial.print("Counting:");//Write the text counting
 Serial.println(i);//Print out the value of i and start a new line after
 delay(1000);//Wait 1 second
}

Serial.println("For loop complete");

}

Let’s see what the output gives us on the serial monitor.

There you have it! Now we can count to 10, without having to use our brain!

 

passive income idea

Make Money With Reseller Hosting

A survey by NetCraft, in 2012, showed that there were 51 million websites launched during that year. That’s 140,000 websites per day! You can learn how to take advantage of this massive growth, and earn passive income by setting up a simple reseller hosting website. I personally use Hosting24, and I’ve been nothing but satisfied ever since.

I personally host 4 domains through them, a VPS, and a reseller account. My reseller account has worked flawlessly for my personal and customer accounts. I’ve had nothing but luck with Hosting24, and I couldn’t be happier with the service I’ve received.

Why promote them and not myself?

Normally you would think I’d be more excited to share my own hosting with you, but I want to share and relate with you about how exciting it is to make money from things like this. Once you have your reseller account set up with Hosting24, it’s basically done! You can host unlimited websites with the available packages, and they offer unlimited bandwidth and disk space.

I’m new to web business, what about support?

I switched to Hosting24 about 4 years ago now, and I’m blown away by their 24/7 customer service. You receive replies within minutes! I’ve learned an amazing amount from their knowledgeable staff, and I’ve been 100% satisfied with every support request I’ve been a part of.

Another key feature is how slick the WHM and cPanel setup is. Your customers each get their own cPanel, and it is set up automatically when you make a sale. You can get a marketing system set up with workflows that automate the entire process for you. This means that 100% passive income.

What is passive income, and why is this so cool?

Most passive income strategies include things like starting a blog, constantly repining affiliate links, completing tasks for people online, writing books and ebooks, dropshipping, etc. What is passive about those? Nothing! A lot of times, when you hear the words “passive income”, you find that there is nothing passive about them. That drives me crazy, don’t say passive, if it’s not passive!

A reseller hosting plan with Hosting24 can be completely passive. You literally set up your site, pick prices for your plans, put them on the market, and make $$$. I cant believe how simple of a business this is to get started with.

passive income idea

My dream

My dream as a young adult was always web hosting, db hosting, etc. I’ve always had something in the back of my head telling me, this is what I need to do. I always thought about renting a warehouse, getting fiberoptic internet, and buying a whole bunch of servers to host people’s websites. Do you know how much work that is? I do, I’ve done plenty of research.

Hosting24 handles all of these things for you. You don’t have to set up complicated web servers and services, no paying rent on a building, no huge internet bills, no server costs, and no maintenance! They do everything for you, how easy is that?

Sign me up then!

You can sign up today to make endless amounts of 100% passive income for as low as $25.99/month. Compare that to the internet alone that you’d have to pay for to do this yourself. It would be a much higher cost than that.

The deployment is simple when you sign up right now, the price is only $25.99, that’s $10 off of the original price of $35.99. I’ve been working with Hosting24 to get a deal like this for a long time now, don’t miss out!

Arduino Statements

Arduino – Switch Statements

The switch statement, in Arduino programming, is very similar to the if statement that I wrote about previously. The main similarity is that you’re testing a statement, if it equals true, certain code is ran.

The difference is versatility and ease of use. When looking at a switch statement, it appears to be much more complicated than an if statement. It’s not! Actually it is much more simple to use, and produces a lot less code.

You will thank yourself later for making the switch, the switch statement switch.

What is it?

Without showing you any code right away, I’ll explain what it is in human language.

A switch statement takes a variable as an argument, and evaluates it. The actual switch part comes after. Now that it knows what it’s dealing with, it looks at the possible matches that you’ve preselected. When it finds a match, it runs the code until it comes across the word “break”. The break makes it skip the whole rest of the switch statement.

If there is no match, it runs the default code. The default code can be blank, and doesn’t have to contain anything juicy. A lot of the time, my default code just outputs to serial saying there was no match.

Uses

An example, where you would use a switch statement in the real world, could be in actual smart home light switches. Maybe you have a function that toggles them off and on when your cell phone app communicates with the arduino.

You could have the communication set a variable based on what button was pushed. Then the variable gets passed in to the switch statement. The switch statement sees the variables value of “living room” and associates it with what it knows, which may be switch number 3. Then inside your statement it can set variables and call functions based on switch 3.

And then you have light on, light off. This statement can reduce a lot of code, where you may otherwise have to write a function or if statement multiple times.

Or you may decide to put the switch statement inside the function, which would produce the same result as the function being inside the switch.

Usage

This begins with a variable that you’re going to test. This variable can be anything, an int, a string, char, etc. You start the switch statement with “switch (var)”. The “var” is where you’d place the name of your variable.

Much like other things you come across while programming for Arduino, you place the code to be run in curly braces. { and }

The difference here, from the other statements, is that the conditions that you are testing reside inside the curly braces. Normally your arguments would go inside the parenthesis, not today!

The way you compare what your variables value is, looks like this: “case condition1:”. You’d replace condition1 with the value you’re testing against your variable. For example, if you’re trying to see if a string says “taco”, you’d replace condition1 with the word taco. It would say “case taco:”.

Ending each code block after you define your case is very important. You end it with break;. If you do not break out of your code, either the compile will fail, or you’ll end up with unexpected results. This is the only time you do want to break your code, instead of fixing it.

 

The last part of this is the default portion. You define the default code to be run by calling “default:”. Any code between the “default:” and the “break;” is run if none of the other things you defined turned out to be true. Sometimes there are errors that cause the variable not to be set right, sometimes you planned on using default for multiple cases. Whatever the case is that you’re using default, you will know. I’ll say again, that you do not have to use the default section. It does need to be there, but it can be simply “default: break;” if you want your switch ignored when nothing is true.

Examples

This example will be assuming the ability to read based on the age of the person. We’ll start by defining the age variable:

int age = 0;

Then we’ll initialize Serial 0, so we can output to the pc:

void setup() {
 
Serial.begin(9600);//Initialize pc communication

}

In the loop we tell switch what variable we’re testing, and what each condition will do. In this case we’re just outputting different words to the serial monitor. After the switch statement is over we do age++, this simply increments the int by 1. You can increment any int this way, and if you have it being done in loop, it’ll just keep on adding. After we have a 5 second delay, before the loop starts over again.

void loop() {

switch(age) {
 case 1:
 Serial.println("You're only 1, how can you read this!");
 break;
 case 2:
 Serial.println("You're only 2, you can talk, but surely still can't read.");
 break;
 case 3:
 Serial.println("You are 3, I'd be pretty impressed if you could read.");
 break;
 case 4:
 Serial.println("You're 4, you may be able to read, but I still don't believe you.");
 break;
 case 5:
 Serial.println("You're 5, I guess it's time to start reading.");
 break;
 default:
 Serial.println("You are either older than 5, or younger than 1. Do whatever you want, I guess...");
 break;
}
age++;
delay(5000);//wait 5 seconds
}

I’ll paste the entire code now, if you’re copying and pasting it, you can use this one:

int age = 0;

void setup() {
 
Serial.begin(9600);//Initialize pc communication

}

void loop() {

switch(age) {
 case 1:
 Serial.println("You're only 1, how can you read this!");
 break;
 case 2:
 Serial.println("You're only 2, you can talk, but surely still can't read.");
 break;
 case 3:
 Serial.println("You are 3, I'd be pretty impressed if you could read.");
 break;
 case 4:
 Serial.println("You're 4, you may be able to read, but I still don't believe you.");
 break;
 case 5:
 Serial.println("You're 5, I guess it's time to start reading.");
 break;
 default:
 Serial.println("You are either older than 5, or younger than 1. Do whatever you want, I guess...");
 break;
}
age++;
delay(5000);//wait 5 seconds
}

Let’s see what happens when we run the code!

switch output

Exactly what we were hoping for! It counts from zero to a bazillion, and correctly chooses what switch condition to use.

Let me know if you have any questions below! More than happy to answer them.

Arduino Statements

Arduino – If Statements

Welcome to If Statements! This is where you will learn to argue with your Arduino about whether or not a statement is true. If statements are very commonly used, get to know them well. Disclaimer: You will not win an argument with your Arduino, it always knows if a statement is true or not. This is similar to marriage, you may find yourself upset if you choose to argue with your Arduino.

What you need:

What is it?

An If Statement is a block of code that gets run depending on an statement you supply to it. If the statement is true, the block of code is run. If the statement is not true, it skips the block of code.

If you supply an else if statement, it will test that statement to verify if it’s true.

If that else if statement is false as well, and you supply an else statement, it will skip to the else statement and run that code block.

You don’t have to supply an else if statement, if your first if statement is false, it will go directly to else. You also don’t have to supply an else statement, if the first if statement is false, it would just not run the code at all without an else statement.

Uses

A good example of an if statement would be in a weather monitoring application. You could have a device monitoring the temperature, and if the temperature is below 32 degrees Fahrenheit, it will tell you ice is possible on the roads. An else statement for this could be an output stating that the roads should not have ice on them.

Another example would be when using an RFID tag. You could have a list of acceptable RFID tags, and if the one that is scanned belongs to the list, the door opens. An else statement for this would be a red blinking LED, that indicates a RFID tag that is not allowed access.

Usage

Lets look at the anatomy of an if statement.

The syntax from Arduino.cc looks like this:

if (condition)
{
  //statement(s)
}

Statement to be tested

Declaring the statement starts with “if ()”, you must have parenthesis here. In between the parenthesis, you put the condition that you’re testing. An example would be “if (x > 10)”. If x is 11, it would run the code. If x is 1, it would not run the code.

Code to be run

The second part of this is the curly braces { and }. This is where you put the code to be run. Anything outside these braces will be run, regardless of whether the condition is true. Inside the braces is code to be run if the statement is true.

If the If gets run, the others are ignored

The main thing to remember here, is that if any if statement equals true, the code gets run and any other part of the if statement is ignored. This means that it skips any else if, or else statements.

Examples

Simple predefined variable:

This example uses a predefined variable, which is an integer named age. This variable is declared right at the top of the following code. Here we’re trying to figure out if the person is old enough to drink. In this case the person is 14, so it should determine that the persons age is under 21, and run the else statement.

int age = 14;

void setup() {
 
Serial.begin(9600);//Initialize pc communication

}

void loop() {

if (age < 21) {
 Serial.println("You are not old enough to drink!");
}
else {
 Serial.println("You are 21 or older, you may have a drink.");
}
delay(5000);//wait 5 seconds
}

Let’s run the code, and see what we come up with. If you’re unsure how to upload code, check out my hello world post. Here is the output you should expect from the above code:

Success! It determined that we are unable to drink.

Let’s change the age variable to 24 now, and see what we get.

int age = 24;

The Arduino wins again! If statements are very useful when writing Arduino sketches. You’ll find yourself using them quite often. Let me know in the comments if you have any questions, and please subscribe for additional Arduino tips.

If you’re looking for something a little more versatile, you may try Arduino Switch Statements.