Send Emails

Sending emails in PHP is extremely easy. Before we get to sending emails, let’s think about why we might want to send an email in the first place. A simple contact form obviously requires an email to be sent. After a user creates an account, we probably want to send them an email so they can confirm their email address. There are many other uses of sending emails, but I don’t want you using email for the wrong purposes. Sometimes, you will see emails being awkwardly used for data storage rather than be alerts or some type of communication. Ultimately, a database is clearly a better way to do data storage and emails are great for communication.

Sending an Email

Now that we know why we might want to send emails, let’s start sending some. You might notice that sending emails is disabled in the PHP Notepad. Well, that is so spammers don’t use AfterHoursProgramming.com to send their junk mail. Anyways, let’s see an example.

Example
	mail('[email protected]','I am the Subject!','I am the message');

Like I said, sending emails is easy with the mail(). All you need to provide is what email address you are sending the email to, the subject, and the message.

Email Headers

Sometimes, we want to send more than just the subject and message to someone. Maybe we want to provide a return address or send an HTML email. Well, these extra parameters all go in the email header. First, let’s just try to setting the return address.

Example
$headers = "From: AfterHoursProgramming.com \r\n"; 
$headers .= "Reply-To: [email protected] \r\n";
mail('[email protected]','I am the Subject!','I am the message',$headers);

So, all we did was to add another variable, $headers, to our mail function. The new variable joined two strings of text. First, we set who the email is from and then set the “Reply-To” to another email address. So, this email will say that it is from “AfterHoursProgramming.com”, but when you reply to the email, your response will go to “[email protected]”.

HTML Emails

Sending HTML emails in PHP is pretty simple as well. We need to add a few more lines to our $headers variable and edit our message. Let’s take a look at an example.

Example
$headers = "From: AfterHoursProgramming.com \r\n"; 
$headers .= "Reply-To: [email protected] \r\n"; 
$headers .= "MIME-Version: 1.0 \r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1 \r\n";

$message = '<html><body><h1>After Hours Programming</h1></body></html>';
mail('[email protected]','I am the Subject!',$message,$headers);

After we set MIME type, Content Type, and the charset, PHP will just add these into the email header. Whenever an email service receives the email, it will check these parameters in the header and display the email as HTML. Don’t forget that you can use the style attribute to format your HTML email.

Introduction

First off remember that PHP pages are not limited to purely writing PHP code. The PHP code is only inside of the <?php and ?> tags. Anything outside of those tags would not be PHP and could be anything that you could normally write in an HTML file. With a standard PHP file that is not going to be used as an include, you will have html tags in the file.

I am sure you know something about file types if you have made it this far. Simply put, make sure your files have the .php extension or else the server won’t process the code. If PHP is your first language other than HTML, CSS, and JavaScript, you will realize that PHP isn’t nearly as forgiving. Be consistent and use the proper syntax. Enough chatter, let’s write our first PHP script!

Example
<html>
    <body>
        <h3>My First PHP Code</h3>
        <?php
            echo "I am awesome!";
        ?>
    </body>
</html> 
Result

I am awesome!

The command echo is one of the ways PHP can output content. So, basically we used the opening <?php tag to indicate that were starting to use PHP code. Then, we echo a string “I am awesome!”, which you are. And of course, we end our only statement with a standard ;. Finally, we tell the server that we no longer want to use PHP code and we close it with the ?> tag.

If you have this idea mastered, continue on to learn about the fundamental stones to craft a master PHP website.

PDO

In PHP, working with databases using the PDO class is one of the best ways to create a dynamic website. Now, it should be worth mentioning that to work with databases, you need to know how to talk to a database. Please review the SQL tutorials before attempting to use databases in PHP. In SQL, we talk to databases primarily using queries. It has its own syntax and structure that is pretty logical. However, it is also very sensitive because it deals with all of your data. SQL injections can ruin your life. No worries. PDO has a couple of excellent ways of overcoming SQL injections. Before we get started, I will not covering all of the SQL queries because I just want you to get the idea. Now, Let’s get started:

Database Connection

A database connection is always required to talk to a database because I mean, we have to know what data we want to work with right? Now, we need to know a few identifiers to access the database, including the location of that database, the database name, username, and password. You should be able to figure all of these out from your hosting provider. It would be too difficult for me to show you how to find them because of the tons of hosting companies that all do it differently.

Example
$host = 'myHostingURL.hostedresource.com';
$dbName = 'databaseName';
$username = 'myUsername';
$password = 'topSecretPassword';

$dbCon = new PDO("mysql:host=".$host.";dbname=".$dbName, $username, $password);

Now, you have to change those variables to whatever database settings, username, and password you have. Let’s figure out what the heck is going on here. After the configuration variables, we use $dbCon = new PDO and pass in our various parameters. Of course, you don’t have to split it up like I did, but that makes it much easier to modify down the road. Basically, this is how you set up your link to the database. Your $dbCon variable is now an object of the PDO class. We’ll talk more about this as we see it in action. This is the absolute link to anything and everything you want to do with your data in the database. That is fantastic, but I want to see some data!

Retrieving Data From a Database

Example
$sql = 'SELECT * FROM tableName';
$stmt = $dbCon->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch())
{
    echo  $row[0] . " | " . $row[1] . " | " . $row[2] . "<br/>";
}

The $sql variable simply holds our SQL that we learned how to create in the SQL tutorials. tableName is just the name of the table in our database (yours will probably be different). After this, things start to get interesting. As I said earlier, PDO is a class, which means we create an object from the PDO class. Objects in PHP use the -> syntax to use a method in that class. So $dbCon->prepare($sql) is calling the prepared method, passing in our SQL. We save that to a new object $stmt so we can now can focus on a particular query. Then, we use $stmt->execute() that tells PHP to run the query. In our while loop, we use the somewhat complicated $row = $stmt->fetch(). Basically, what we are doing here is setting a variable $row equal to each record that is returned until there are no more records left. $stmt->fetch() is just getting one record at a time. Finally, we echo out results out using an index on the column names. So for example, $row[0] will return the first column of that record, $row[1] will return the second column, and so on.

Inserting Data

Inserting data pretty much follows the same flow as the SELECT query we just ran. However, I am going to use this type to introduce you some of the awesome things about PDO. If don’t know what SQL injection is, it’s basically whenever someone injections SQL into one of the POST or GET parameters. This is a problem for novice coders, because they might directly put that variable in the query without escaping it, which means someone can modify your SQL query! Instead, PDO lets you escape the query easily.

Example
$sql = 'INSERT INTO tableName(column1,column2) VALUES(?,?)';
$stmt = $dbCon->prepare($sql);
$stmt->execute(array('aaa',"bbb"));

Now, that doesn’t look quite like SQL you might say. Notice the ? in the query. Well my friends, that is the beginning of the awesome “PDO factor”. We are simply telling PHP, “Hey, we are going to give you these values in order later”. So, we just move on and prepare our statement like we are cool. Finally, we get back to telling PHP what exactly we are talking about with that query. In our execute, we pass an array with the values in the order we have the question marks. Pretty awesome, huh? Note: the the column1 and the column2 are just the names of your columns. I must admit there is a little bit of a better way to do this without question marks.

Example
    $sql = 'SELECT * FROM tableName
            WHERE columnName = :myVar';
    $stmt = $dbCon->prepare($sql);
    $stmt->execute(array(':myVar'=>'someValue'));
    $row = $stmt->fetch();
    print_r($row);

This is a SELECT query, but we can still pass variables into it. We just replace the ? with our new variable :myVar. Note: the : is important, as it specifies that we are using a temporary variable. Then later in our execute statement, we can tell PHP what we meant by that variable by placing all of those variables in an array and placing that temporary variable as a string in our index, and the intended value of that variable after the =>. The point of the array is so we can pass in many values into our SQL query. For now, this concludes using PDO, but there is so much more for you to learn in the following resources. Try to go through a little bit of the official documentation to get a real feel for how to use PDO.

References

Break and Continue

While not used very often in PHP, continue and break deserve much more credit. Continue and break provide extra control over your loops by manipulating the flow of the iterations. Continue is the nicer one of the two as it prevents the current iteration, or flow through one pass of the loop, and just tells PHP to go to the next round of the loop. Break provides more aggressive control by completing skipping out of the loop and onto the code following the loop. If you have ever played the card game UNO, continue is basically the skip card, and break is someone slamming their cards down screaming I am the winner and leaves the room. Let’s go through some examples to see how to use them.

Example
$i = 0;
for ($i = 0;$i <= 5;$i++)
{
    if ($i==2)
    {
        break;
    }
    echo $i;
    echo "<br />";
}
echo "End of for loop" ;
Result

0
1
End of for loop

Once the var $i reaches 2 in the for loop, it meets the conditional statement $i == 2, which is then executed. The statement executed is break;. When break is executed it actually breaks us out of the for loop, which is why when $i equals 2 we exit the for loop and execute echo “End of for loop”; instead of ending the for loop when $i equals 5. Remember break escapes the entire logic of the other iterations.

Example
$i = 0;
for ($i = 0;$i <= 5;$i++)
{
    if ($i==2)
    {
        continue;
    }
    echo $i;
    echo "<br />";
}
echo "End of for loop" ;
Result

0
1
3
4
5
End of for loop

It seems pretty obvious that continue is different than break. Notice how the only result not printed is 2. The continue basically says let’s skip out of this particular instance of the loop and move onto the next one. When we are running through the instance where $i becomes equal to 2, we meet the conditional statement if( $i == 2) where it is true. Then, we execute the continue, which stops us from executing the following statements in the loop. We then run through the next iteration of the loop where $i equals 3. Since we don’t meet the conditional statement this time, we write the following statements and will never enter into conditional if($i == 2).

PHP Quiz

Taking a quiz or a test an excellent way to test your own knowledge of a subject. We believe that our exams are completely fair and require significant knowledge to achieve a perfect score.

PHP Quiz

PHP is one of the most dominant scripting languages on the web because it is essentially free. PHP also has one of the highest rates of new coders compared to other languages because young coders prefer to start in a language that won’t cost them any money. PHP performs well in terms of speed and flexibility, which helps the new coders stick with the language. The PHP quiz is designed to determine if you have understand the fundamentals of PHP. Once you have mastered the basics of the quiz, you should explore using PHP on your own for a little while. When you have finished tinkering with PHP, you might want to consider moving onto database programming languages like SQL, and taking the SQL quiz.

Begin Quiz

PHP Tests and Exams

We currently only provide a standard PHP quiz that isn’t exactly a professional testing mechanism. This means that if you are trying to test someone’s PHP knowledge this exam is not for you. It does provide an excellent overview of PHP, but it is intended for self-development. However in the future, we might integrate a testing system into After Hours Programming, but we are not currently working towards that goal. For now, we have created a simple practice test to check your understanding of PHP.