Category: Code Snippets

How to vertically center text in CSS Grid and Flexbox

Take this simple HTML: And, some basic styling: It looks like this: Now, we want to center this text vertically. The first modern approach you can take is with flexbox. Just add these two lines to .parent: And, you get this: Simple. It’s very similar with CSS Grid: And, you can add as much text as you want and it’ll get vertically-centered properly. Like this: So, there you go. That said, if you want to go on learning even more HTML and CSS, check out my Website Template course on Skillshare. You’ll learn CSS Grid, CSS transitions, asynchronous requests in

Read More »

How to Style HTML Input Placeholders In CSS

Let’s start with the HTML: So, now we want to style the placeholders themselves. If you want to keep it simple, most modern browsers support this: You can use the ::placeholder pseudo-class like any other. For older browser support it looks like this: So, let’s look at a real-world example: A simple form. Nothing fancy, but notice the placeholder text for the required email field is a different color. This is one simple example of how you might use something like this. Here’s the full HTML: And, here’s the full CSS: So, there you go. Now, speaking of real-world examples,

Read More »

2 ways to horizontally center a DIV in CSS

Let’s take this simple HTML structure: The first method involves some straight-forward CSS: Doesn’t get much simpler than that: And, if it this is all you need to do, you can probably stop here. But, sometimes what you’re actually trying to do is a little more complicated and you need some more flexibility. Enter CSS Grid: Here, we’re creating a grid with 1 column that fills the entire space of the parent DIV. Then, a child DIV with a 60% width. And, using justify-items to center the child DIV. This might seem like overkill for something this simple, but it

Read More »

Ajax requests with jQuery.post()

This is one of the reasons I still like jQuery. I’m sure all the new frameworks do similar stuff, but things like this are so simple with jQuery. Anyway, jQuery.post() is a shorthand Ajax function. It’s the equivalent of doing this: $.ajax({ type: “POST”, url: url, data: data, success: success, dataType: dataType }); So, with it, you can send an Ajax request this easily: var posting = $.post(url, data); Then, handle the response like this: posting.done(function(data) { // Handle data here }); Or, all together like this: $.post( “process.php”, function( data ) { $( “.result” ).html( data ); }); It

Read More »

The One-Line Difference Between Ugly and Amazing Websites

Forget personal taste. I’m telling you as sure as I’m sitting here… whatever your personal thoughts about the differences between this before and after… one will get you, “Um well… something just feels off.” And, the other: “Wow! Clean, fresh. Amazing!” It’s just how people are. Anyway, here’s the before: And, here’s the after: This is a template I’m working on for a new course I’m doing. And, the difference is a single CSS declaration, but it’s light-years in terms of how it looks and how clients will react to it. The code? body, p, h1, h2, h3, h4, h5,

Read More »

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 »

jQuery Smooth Scroll to Anchor Using animate()

I always get a kick out of jQuery… especially animation methods. It’s one of those things that just wows clients… and truthfully, I feel pretty cool watching the animations run on a site. That said, much of what you can do with jQuery animations is more than “eye-candy”… they help enhance the user experience. This is one such animation: smoothing scrolling to an anchor tag. Instead of that abrupt flash you get as default behavior in a browser… you get a nice smooth scroll that gives a site visitor some context about what they just clicked and where they’re ending

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 »

jQuery: Find An Anchor By Its HREF

jQuery selectors can be a bit tricky. :first-child, :last-child, nth-of-type, is it zero-based, why is it grabbing that element when I expected this one. Fun stuff. On a recent project, I needed to find an anchor tag by its href so I could then replace it with my own URL… and that got me thinking about jQuery selectors again. So, let’s run through some and try to clear up some confusion. Here’s this week’s Tech Tutorial: 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

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 »

Add Active Navigation Class to Menu Item Based on URL Using jQuery

In this jQuery tutorial, you’ll learn how to add an active class to a menu item based on the page URL using jQuery… so you can highlight that menu item. You’ll learn: how use the jQuery addClass() method how to get the current page’s URL path in JavaScript how to split a URL in an array of parts how to use the JavaScript pop() method how to target an element based the value of a specified attributed using jQuery Watch the tutorial below: Links mentioned in the video: Link to the Complete Web Developer Course with discount. My web developer

Read More »

Set DIV Height to 100% of Its Parent Using jQuery

In this jQuery tutorial, you’ll learn how to set the height of a DIV to 100% of its parent. You’ll learn: how to set variables and target selectors how to get and set div height using height() how to target multiple selectors at once Watch the tutorial below: Links mentioned in the video: Link to the AJAX course mentioned My web developer resources page with more code snippets 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 »

jQuery Tutorial: How to Build a jQuery Accordion

In this jQuery tutorial, you’ll learn how to build a jQuery accordion. You’ll learn: how to slideUp() and slideDown() different elements how to use relative selectors to target elements in jQuery how to use the click event to trigger functionality on click Watch the tutorial below: Links mentioned in the video: Link to the AJAX course mentioned My web developer resources page with more code snippets 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 »

Responsive Web Design: Building a Responsive Menu

In this responsive web design tutorial, you’ll learn how to build a responsive menu. You’ll learn: how to target different breakpoints with media queries how to write the CSS to “flip” the menu from vertical to horizontal view at those breakpoints how to use jQuery to create a responsive navigation icon that toggles the mobile menu Watch the tutorial below: Links mentioned in the video: Discount link to Rob’s Complete Web Developer Course My review of the the Complete Web Developer Course My web developer resources page with more code snippets Here’s the code I used in the video: If

Read More »

jQuery Tutorial: Submit a Form and Post Data Using jQuery and AJAX

In this jQuery tutorial, you’ll learn how to submit a form, post the data and format the response using jQuery and AJAX: Here’s the code I used in the video: Index.php Process.php If you enjoyed this tutorial and want to keep learning, check out my free tutorial site here: https://johnsfreetuts.com

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 »

Pure HTML and CSS Dropdown Menu

Here’s how to create a pure HTML and CSS dropdown menu: 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 »

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 »

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

Xan Barksdale

Xan Barksdale

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

Bob Patterson

Not only is John a very talented programmer and developer, he is also an excellent communicator. He has a talent for taking complex subjects and communicating them in terms that anyone can understand. This is a rare combination. This ability has enabled me to take my skills and knowledge to the next level. Thank you John for for all that you do.

Thabo Motsoahae

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

Bradley Smith

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

Sukh Plaha

John is a fantastic and patient tutor, who is not just able to share knowledge and communicate it very effectively – but able to support one in applying it. However, I believe that John has a very rare ability to go further than just imparting knowledge and showing one how to apply it. He is able to innately provoke one’s curiosity when explaining and demonstrating concepts, to the extent that one can explore and unravel their own learning journey. Thanks very much John!

Daniel Mohlendick

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

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.

Jason Rumley

Jason Rumley

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

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.

Chris Aitken

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

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.

Aaron Gott

Aaron Gott

John has a particular knack for the development and training of others.

Michael Skye

Michael Skye

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