Category: PHP Code Snippets

Send PHP Email Using PHPMailer

PHPMailer is a popular open source, email-sending library used by applications like WordPress, Drupal, SugarCRM, Joomla and others. This tutorial will show you how to install PHPMailer, set up SMTP and send email in PHP using PHPMailer.

Read More »

PHP Add To and Remove Elements From an Array

In this tutorial, I’ll show you eight different ways to add to, remove from and insert elements to/from an array in PHP. PHP array functions used include: array(), array_push(), array_unshift(), array_pop(), array_shift(), array_slice(), count(), array_diff() and array_splice().

Read More »

What object-oriented programming is NOT

Object-oriented programming is MORE (much more) than knowing how to write a class. It’s about how you build your applications. I call it an “approach”… but it’s an approach *to application-building*.

Read More »

Output the last row inserted in MySQLi

MySQLi makes grabbing the last inserted row easy. After running your insert query, you can do this: $id = $mysqli->insert_id; Then, you can query for that row like this: $result = $mysqli->query(“SELECT * FROM table_name WHERE ID = {$id}”); And, fetch the result as an object: $user = $result->fetch_object(); From there it’s a simple echo to output it to your page: echo $user->user_name; (Although, you’ll want to use htmlspecialchars or htmlentities to escape the output and prevent XSS attacks. But, we’ll save that for another day.) Simple. Anyway, in the newly released Module 3 of PHP 101, I show you

Read More »

Connecting to MySQL with PDO

With MySQLi, it looks like this: $mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name); But, PDO is a bit different because it can interact 12 different types of databases: Oracle, PostgreSQL, SQLite, MySQL, Cubrid and several others. So, when using it you have to specify which driver you want to use. Like this: $conn = new PDO(“mysql:host={$db_host};dbname={$db_name}”, $db_user, $db_pass); Notice the “mysql:host=” bit. For different drivers, you just change out the “mysql” part. So, PostgreSQL would be: $conn = new PDO(“pgsql:host={$db_host};dbname={$db_name}”, $db_user, $db_pass); For Oracle, it’d be: $conn = new PDO(“oci:host={$db_host};dbname={$db_name}”, $db_user, $db_pass); And, so on. Nice thing is… The code

Read More »

Simple input filtering in PHP

Here’s one I don’t see talked about much: $name = filter_input(INPUT_POST, ‘name’, FILTER_SANITIZE_STRING); What this does is grab the “name” element from your POST array and run it through the the filter: FILTER_SANITIZE_STRING… which removes all HTML tags from the string (since we know a person’s name doesn’t have HTML in it). It’s a really simple way of quickly filtering your data. Here’s another: if ( ! $email = filter_input( INPUT_POST, ’email’, FILTER_VALIDATE_EMAIL ) ) { die(‘Invalid email’); } This one validates the submitted email address. And, returns false if it’s invalid. Again, a very simple way of quickly validating

Read More »

Prevent SQL injection attacks with prepared statements

Bit of a hot topic lately in my inbox. Here’s what an old, vulnerable query might look like: $expected_data = 1; $query = “SELECT * FROM users where id=$expected_data”; $result = $mysqli->query($query); The problem here is we’re injecting user-submitted data directly into our SQL statement without any sort of escaping or validation. So, a hacker could enter something like this in our form: 1; DROP TABLE users; Changing our full query to: SELECT * FROM users where id=1; DROP TABLE users; Which, as you can probably see, will execute the SELECT statement but then drop our users table. No bueno.

Read More »

How to Create Tweets Using the Twitter API

I’m going to quickly show you the exact code to send a tweet using the Twitter API. Then, how to learn to build a full-fledged Twitter app. Let’s dig in. Before you start, you need three things: A developer account on Twitter. (dev.twitter.com) A Twitter app for the API keys and access tokens (apps.twitter.com) The Twitter OAuth PHP class (twitteroauth.com) Download the class to your working folder. Then, create a file called index.php (or whatever you want) and include the Twitter OAuth class like so: require “twitteroauth/autoload.php”; use Abraham\TwitterOAuth\TwitterOAuth; Next, we need to connect to the API: $connection = new

Read More »

PHP cURL Tutorial and Example

A simple PHP cURL tutorial and example. Learn how to use curl_init, curl_setopt, and curl_execute. Also learn how to POST data to a remote URL using cURL. Ready to learn even more PHP? Take my free Beginner’s Guide to PHP video series at http://johnmorrisonline.com/learnphp Get this source code along with 1000s of other lines of code (including for a CMS, Social Network and more) as a supporting listener of the show at http://johnmorrisonline.com/patreon P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my

Read More »

PHP 7’s Null Coalescing Operator: How and Why You Should Use It

PHP 7’s null coalescing operator is handy shortcut along the lines of the ternary operator. Here’s what it is, how to use it and why: Ready to learn even more PHP? Take my free Beginner’s Guide to PHP video series at http://johnmorrisonline.com/learnphp Get this source code along with 1000s of other lines of code (including for a CMS, Social Network and more) as a supporting listener of the show at http://johnmorrisonline.com/patreon P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, source

Read More »

The Thing About PHP 7’s Spaceship Operator

Subscribe So You Never Miss An Episode [saf] May the force be with you… 😉 Unless you’ve been under a rock (which is totally cool if so) you know PHP 7 has been out for a bit now. I finally took some time the other day to fire it up on one of my dev servers and see what all the fuss is about. Online, I’d kept hearing about this “spaceship” operator. This thing’s kind of cool actually. Let me show you. So, here’s a common bit of code you might see pre-PHP7: This is a sorting routine. usort() lets

Read More »

TUTORIAL: How to Build an Advanced Website Template Using PHP and Bootstrap

INSPINIA has sold 29,598 units at $18 a piece. That’s $532,764. SmartAdmin sold 20,136 units at $12 a piece. That’s $241,632. Unify… $321,828. That’s just three of over 800 Bootstrap templates on WrapBootstrap. And that’s just one Bootstrap marketplace. Obviously, people want these things. But, they all have a major problem. One that makes it hard for clients to actually implement on their site, makes updates horrifying and ensures after-launch tweaks are a nightmare. I’ll show you how to fix that problem and turn these basic template into advanced “site-builders” using a little PHP magic. You think maybe you could make

Read More »

TUTORIAL: Submit Online HTML Form to Both MySQL and Email Using PHP

In 2011, online survey giant, SurveyMonkey, acquired Wufoo Forms for 35 million. SurveyMonkey itself does 113 million  a year in revenue. And, it’s valued at nearly 1.35 billion. Both of these services serve a simple purpose: creating online forms. And, they’re not the only players in the market. How much of that market would you need to siphon off to make more money than you probably ever imagined? It’s what I tell developers all the time. Focus on one thing. Get really good at it. Cash in on that one skill until it runs dry. Lather. Rinse. Repeat. So, would

Read More »

PHP Fatal Error [FIX]: Call to a Member Function Fetch_Assoc On a Non-Object

I remember this annoying error like it was yesterday. It always baffled me a bit when I first started learning PHP (I know… N00B!): Fatal error: call to a member function fetch_assoc() on a non-object. It was always the line number that tripped me up. Anyhoo, here’s what’s really going on and how to kill this error dead once and for all: And, if you’d give me a likey-like I’d sure appreciate it! And like I said the source code is available on Patreon for the smart folks who support the show. (You know you wanna join them.) P.S. If you liked the show,

Read More »

3 Ways to Verify an Email Address Using HTML, jQuery and PHP

When you verify an email address, there’s really three things you want to do: Don’t submit the form unless the email address is valid Give hints about what’s wrong and how to fix it Make sure malicious data doesn’t get into your database Well, here’s a handy little snippet that does all three using HTML, jQuery and PHP. Feel free to use this how you need in your projects. And, if you want it you can get the source code as a supporting listener on Patreon. Anyway, here’s the video… see what you think: And, if you’d give ol’ JMO a like I’d

Read More »

How to Get the First Value In An Array Using PHP When You Don’t Know the Keys

Arrays are like that crazy uncle who gets a little too drunk at Christmas and starts telling inappropriate jokes at the dinner table. You love ’em… but you hate ’em. You can efficiently store and grab tera-tons of data with them… but when you just want to get the value of the 2nd element in the 3rd dimension of one… you feel like you gotta break out the code-jitsu to get at it. Have no fear! Captain JMO is here! I just cranked out a new video for you showing you several different ways to get at different keys and

Read More »

Grizzly Bear Rips Freelancer to Shreds. You Take His Job

Subscribe to the Podcast [saf] Here’s the big thing to get to succeed as a freelance web developer: If you and your buddy are hiking in the forest and are suddenly attacked by a grizzly bear… you don’t need to be the fastest guy in the world. You just need to be faster than your buddy. There’s your uber-secret, stop-the-presses secret to success. Freelancing is a competition. To win, you don’t need to be perfect… you just need to be better than the next guy. And, let me tell you… most of your competition is epicly bad at this. The grizzly

Read More »

How to Create a Contact Form Using PHP

When you create a contact form in PHP, there’s a couple key parts you need to make sure are in place so the person actually using the form doesn’t want to suddenly get into knife-throwing (at your head) afterward. You need validation that make sense and is easy to understand. I prefer the kind that shows up all at the top of the form, because when you have a long form and missed one checkbox and have to go hunting through the form like you’re looking for a lost sock… knife-throwing becomes a viable option. Next, you need to make

Read More »

How to Use the PHP DateTime Class Instead of the PHP Date Function

In this PHP tutorial, you learn how to use the PHP DateTime class introduced in PHP 5.2 instead of the PHP date function. Watch the tutorial below: Links mentioned in the video: How to Start a Blog in Less Than 15 Minutes Let me help publicize your blog My web developer resources page with more code snippets. Supported DateTime Formats Supported Timezones Supported Interval Strings DateTime PHP Manual Entry Get the source code for this video as a supporting listener of the John Morris Show on Patreon If you get value from this code snippet, please consider sharing it with another

Read More »

How to Create a Custom Error 404 Not Found Page

In this PHP tutorial, you’ll learn how to create a custom 404 page not found error page. Watch the tutorial below: Links mentioned in the video: How to Start a Blog in Less Than 15 Minutes Let me help publicize your blog My web developer resources page with more code snippets. Get the source code for this video as a supporting listener of the John Morris Show on Patreon If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

Read More »

How to Send Mail Using PHP

In this PHP tutorial, you’ll learn how to send mail using PHP. Watch the tutorial below: Links mentioned in the video: How to Start a Blog in Less Than 15 Minutes Let me help publicize your blog My web developer resources page with more code snippets. Get the source code for this video as a supporting listener of the John Morris Show on Patreon If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

Read More »

How to Parse XML With SimpleXML and PHP

In this PHP tutorial, you’ll learn how to parse XML using SimpleXML and PHP. Watch the tutorial below: Links mentioned in the video: How to Start a Blog in Less Than 15 Minutes Let me help publicize your blog My web developer resources page with more code snippets. Get the source code for this video as a supporting listener of the John Morris Show on Patreon If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

Read More »

How to Create a Zebra Striped Table With Odd Even Row Colors Using PHP

In this PHP tutorial, you’ll learn how to create a zebra striped table by adding odd and even classes in a loop using PHP. Watch the tutorial below: Links mentioned in the video: Link to the Complete Web Developer Course with discount. My web developer resources page with more code snippets. Here’s the code I used in the video: Get the source code for this video as a supporting listener of The John Morris Show on Patreon If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

Read More »

Build a Grid Layout For WordPress Using WP_Query

Here’s how to build a grid layout for WordPress via shortcodes and WP_Query: A lot of WordPress developers immediately rush to query_posts in order to create custom loops. But, query_posts is meant for altering the main loop of a WordPress page/post (actually, it’s not even recommended for that anymore). Using get_posts() is okay… but, if you want that real WordPress flavor using WP_Query is the way to go. In the video above, I show you how to use WP_Query to create a custom loop inside WordPress in order to build a Pinterest-style grid layout. Here’s the code I used in

Read More »

Prevent XSS Attacks. Escape Strings in PHP

Here’s how to prevent XSS attacks by escaping output in PHP: Here’s the code I used in the video: What Is XSS? XSS stands for cross-site scripting and it refers to a type of attack where a hacker injects malicious client-side code into the output of your page. Applications that don’t escape their output are vulnerable to this type of attack. XSS Example A simple example is a blog comment. If not properly escaped, an attacker could enter (for example) JavaScript code into the blog comment. That code would be stored in the database, output to the page when loaded,

Read More »

PHP Try Catch Error Handling

How do you PHP try catch blocks to efficiently handle errors? Here’s the answer: Here’s the code I used in the video: If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

Read More »

How to Create a PHP 301 Header Redirect Script

How do you implement a 301 header redirect in PHP? Here’s the answer and how to do it: Here’s the code I used in the video: If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

Read More »

A PHP Script to Search a MySQL Database

Here’s a tutorial video and script you can use to search a MySQL database using PHP: Get the source code as a supporting listener on Patreon. If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

Read More »

How to Insert Form Data Into a MySQL Database Using PHP

Why won’t my form data insert properly into my MySQL database? Here’s the most common reasons why: Get the updated source code for this video here. Not connecting to MySQL properly Not matching form fields to database columns properly Issues Connecting to MySQL When you run into connection issues, you’ll usually see an error that will say there was a problem connecting to the database. More often than not, it’s simply a typo in your database name, username, or password. Make sure to triple-check that information. Also, keep in mind if you’re using source code I’ve provide you’ll need to

Read More »

How to Validate an Email Address (By Domain) Using PHP

How can I validate an email address (by domain) using PHP? Here’s how: Here’s the class that does all the heavy lifting and an example page for including and using the class: These are the exact steps for using this: Include/require class-validate-email.php into your application or web page. Instantiate a new instance of the validate_email class. Pass the email address to the validate_email::validate_by_domain() method. If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

Read More »

PHP Multiple Checkbox Array Handling

I tend to get a lot of questions around checkbox handling when submitting forms to  PHP. Here’s a simple snippet to illustrate how it works: A couple things to pay attention to here… 1. Notice the input names. They follow this pattern name[key]. The name is really the name of the “group” of checkboxes. The key is the name of that individual checkbox. This is how you know which checkboxes were checked and which weren’t. When submitted, this form will only include the checkboxes that ARE checked. 2. Notice the created array. When this form is submitted the output will

Read More »

A Simple PHP Class For Prepared Statements in MySQLi

Prepared statements are all the rage right now in PHP development… and for good reason. Not only do prepared statements make your queries more secure… they also help future-proof your code by relying more heavily on PHP itself for that security. If you’re not using prepared statements in your queries, you really should be. Here’s a simple class that helps you do just that using MySQLi: I recommend walking through this code and unraveling how it all comes together. There are a few gotchas when using prepared statements in a dynamic way like this. Or you could just check out

Read More »

How to Create an ics Import File Using PHP

In this video, you’ll learn how to create an .ics import file using PHP. This allows you to dynamically generate the .ics file based on stored event data. Users can then download the file and import the event information in their calendar of choice… Outlook, Thunderbird(Lightning), Apple Calendar, etc.

Read More »

How to Sort Multidimensional Arrays Using PHP

In this video, you’ll learn how to sort multidimensional arrays in PHP. You’ll not only learn basic sorting using array_multisort(), but you’ll also see a more advanced custom function for sorting multidimensional arrays by a specific key. Multidimensional arrays can be one of the more confusing parts about learning PHP, but this video will help you get your head around it and give you some tools for sorting your multidimensional arrays that are simple and straight-forward.

Read More »

How to Create an HTML Select Box From a MySQL Results Array Using PHP

This is a question I get quite a bit, so I figured I’d write a post on it: How do I create an HTML select box with options from data in my database? Here’s how: The Query First, let’s look at our query. Yours might look something like this: That will select everything in our table and loop it into an array of objects containing the results. Now, we can take that array and create a HTML select box with it. The HTML Select Box Now, that we have our array of objects from our database we can use it

Read More »

The simple secrets to high-paying freelance clients

What makes clients willing to pay $5,000, $10,000 even $20,000 and up for your services? Download and install my mobile app and I’ll show you. It’s free. Just click the button below:

Clients Like:

Inc. Magazine Logo
Lewis Howes Logo
Ray Edwards Logo

WHAT OTHERS ARE SAYING

Bradley Smith

John and I have worked together on numerous projects. John is very quick and efficient and was a pleasure to work with.

Oliver Wainwright

Oliver Wainwright

I’m a fan. I have completed several of John’s courses. I find him very knowledgeable and he has a great delivery.

Michael Skye

Michael Skye

John is a man of integrity, who gives generously of himself to projects and people he cares about.

Ray Edwards

I recommend John every chance I get. If every person I worked with were as committed to excellence, punctuality, value, and unquestionable integrity… the world would be a better place. Highest recommendation.

Lewis Howes

John is amazing at building membership sites. He converted one of my sites over from it’s existing (hardly working) platform over to the clean and simple to use WishList membership platform. I highly recommend using John and WishList for any of your membership site needs.

Lori Grant

John did an outstanding job on my project. I highly recommend him and look forward to working with him on future projects.

Jason Rumley

Jason Rumley

John has a habit of over-delivering on the expectations he sets up. That’s why he’s the best.

Chris Aitken

He significantly improved my site through his expert knowledge of PHP, CSS and Javascript. Would definitely recommend John to others.

Daniel Mohlendick

On the Freelancing on Upwork course: “This is by far the best course i have watched on Skillshare!! Thank you so much.”

Andrew Malone

Andrew Malone

John Morris is exceptional in his ability to give focused insight into Freelancing and starting one’s business. His direct methods inspire confidence in his honesty.

Jim DeJonge

Jim DeJonge

John has a relaxed and engaging manner. His advice is solid and the explanations are well thought out.

Thabo Motsoahae

John is one of the best instructors I have come across, I learned a lot from his online tutorials.

Xan Barksdale

Xan Barksdale

Very professional worker who is extremely knowledgable in WordPress and Wishlist Member. I would definitely hire again.