How many ways are there to output HTML using PHP

The con, the cat and t’e nation!

Have you heard of concatenation?

No?

Stay with me if you haven’t!

According to wikipedia:

String concatenation is the operation of joining character strings end-to-end. For example, the concatenation of “snow” and “ball” is “snowball”.

Concatenation is an import concept in PHP for outputting HTML. Also used in many other programming languages.

In this tutorial you will learn the many ways PHP can generate and output HTML to the browser.

So your users can view your pages.

There are many ways to output HTML to the browser.

As once you want to output variables and data from your database in well formatted HTML, single quotes and double quotes can cause all kinds of strange problems in rendering the HTML page in the browser if they aren’t coded correctly.

HTML output examples:

1) Straight HTML

Outside of your PHP tags, you simply output straight HTML like this

<?php // Some PHP Code ?>
<p>Hello World</p>
<?php// PHP Code continued... ?>

2) Straight HTML echoed out as string from PHP

Inside your PHP tags, you can output straight HTML like this

<?php
echo "<p>Hello World</p>";
?>

3) Straight HTML echoed out as string from PHP (single quotes within double quotes)

If your HTML needs attribute value pairs, as in the example giving the font a color of red with a style attribute. Then you will need quotes within quotes. In the first line of code, I’m using single quotes within the double quotes of the string.

An alternative is to escape the quotes with a backslash as show in the second line of code. Then you can use double quotes within double quotes. There is a good reason for needing to do this which we will come to in later example.

The first line is definitely easier to read in my opinion.

<?php
echo "<p style='color: red;'>Hello World</p>";
// Alternatively escaping the quotes
echo "<p style=\"color: red;\">Hello World</p>";
?>

4) Straight HTML echoed out as string from PHP (double quotes within single quotes)

As in example 3 above you can use quotes within quotes, but this time the quotes are reversed with the double quotes on the inside.

An alternative is to escape the quotes with a backslash as show in the second line of code. Then you can use single quotes within single quotes.

<?php
echo '<p style="color: red;">Hello World</p>';
// Alternatively escaping the quotes
echo '<p style=\'color: red;\'>Hello World</p>';
?>

5) Concatenating a variable with two strings

Here we take a string variable and concatenate with two other strings of the opening and closing paragraph tags.

<?php
// Create a string variable
$my_message = "Hello World";
// Echo out the paragraph tags, concatenating the string in between them
echo "<p>". $my_message ."</p>";
?>

6) Using an array to output a string within a foreach loop

Inside your PHP tags, you can output straight HTML like this

<?php
// Create a string variable
$test = "Hello World";
// Split the string into an array, each letter will be an item in the array
$arr = str_split($test);
// Echo the opening paragraph tag
echo "<p>";
// Loop through the array
foreach ($arr as $a)
{
// Echo each item
echo $a;
}
// Echo the closing paragraph tag
echo "</p>";
?>

7) Using a function to output HTML

Inside your PHP tags, you can output straight HTML like this by calling a function.

<?php
// Function to return a string
function fnOutput()
{
return "Hello World";
}
// Echo the opening paragraph tag
echo "<p>";
// Call the function
echo fnOutput();
// Echo the closing paragraph tag
echo "</p>";
?>

So there are 7 different ways of outputting HTML to the browser.

Are there more? For sure and I will add more to this list.

Please take the above examples and use them to practice with.

If you think you’ve got some better examples, let me know.

How to get your new website showing in Google search results

You’ve bought your domain name

You’ve worked hard developing up your website.

You’ve launched it, tested it out in your browser.

Sent a link to friends, shared it on social media.

Then you went to Google…

… to search your new domain name and …

it didn’t show up?!?!

You are thinking how’s that possible?

Even when you are searching for the exact domain name!

So how to get your site listed?

Google provides a tool called “Google Search Console

If you haven’t used it before, you can just sign in with your Google account.

(And if you don’t have one of those by now, you will need to create one!)

Then follow these steps you get your site submitted
  1. Click on the red “ADD A PROPERTY” button (property being your website domain name in this case, but you can also add Android Apps here).
  2. Enter the URL of your website address and click the Add button
  3. This will you take you a page to verify to Google that you do indeed own the website
  4. The simplest recommended way to verify is downloading the HTML verification file
  5. Once downloaded you can upload the file to your site, via ftp for example
  6. Confirm it was successfully uploaded and click Verify
  7. Once verified you will be able to access the properties details
  8. Click on the “Crawl” menu
  9. Click on the “Fetch as Google” sub menu
  10. This will allow you to request Google to Fetch your site
  11. Once your site has been Fetched, a button will show up “Submit to index”
  12. Click that button and your site will submitted to the Google Search index!

Then it’s a waiting game, to see your new site listed in Google Search results.

Once your site has been listed, you will be able to see lots of helpful information in the Google Search Console.

There are other tools listed there for telling Google about Structured Data on your site, which I will post about soon!

If you found this helpful or have any questions for me, please leave a comment below.

Essential tech and tools for a new eCommerce site

Assuming you’ve already chosen your eCommerce platform. Below is a list of essentials that you should consider for your new e-commerce store.

If you haven’t chosen a platform already. Some of the main contenders are Shopify, WooCommerce with WordPress, Magento.

If you are selling digital products you could use Gumroad or GoSpaces.

If you are a maker then you should be selling on Etsy.

Below are some of the most useful tools for your eCommerce site:

SSL

Use https / SSL to give customers confidence you are protecting their information on your site. Contact your hosting provider to get them to install SSL for you.

Hosting

Find reliable web hosting like Digital Ocean where you can spin up a “droplet” for as little as $5/mo, RackSpace has a wide variety of hosting options.

Backups

Make sure your hosting has backups enabled and you know how to use them and restore them

Analytics

Enable analytics on your site from the beginning. Even if you don’t look at them to begin with, the data will be a valuable asset in the future. Google Analytics is free, why wouldn’t you use it?

You’ll be able to see where visitors are accessing your site from, what content they are viewing, how long they are spending on your site. Also what technology they are using to access to your site. You are also able to set-up specific eCommerce goals to track. All for free, don’t waste time looking for another analytics solution.

Webmaster Tools

Google Webmaster Tools (now called Google Search Console) gives you more insights and tools into managing your websites presence. You can configure how your site appears in search results. Get tips for HTML improvements. See analytics on searches to your site, lists of other sites linking to your site. Submit your site and sitemap(s) to the Google index. Also view crawl errors and security issues.

Bing also offers it’s own tool: Bing Webmaster tools

SEO

Make sure the basics are there, good quality title tags for each page, keywords and description, image tags

Social

Set-up social media accounts for your site, Twitter, Facebook page and Instagram as a minimum. Of course there are more like Pintrest

Email Marketing

Create an email list, capture email addresses so you can market them, MailChimp is a good platform to start with

Physical Location

If your site has one or more locations, like a retail store. You can set them up on Google Places.

Testing

Test everything, test your check out process, test your contact forms, test regularly and if make updates – re-test.

Backups again!

Take backups before changes, need to update a WP plugin on your Woocommerce store? Take a backup first, it should take minutes with a plugin like ….

Supporting content

Make sure your site has a good FAQ (Frequently Asked Questions) page.

Shipping

If you are shipping products, explain your shipping and return policies.

Make sure HTML is well formed

Use the W3C HTML validator tool, to check your website and it’s pages are producing valid HTML

CSS / Cascading Style Sheets

Use the W3C CSS validator tool, to check your website CSS is valid

Broken links

Use the W3C Link Checker tool, to check your website links aren’t broken

Optimization of assets

Optimize images, javascript, css files, these files will need to be downloaded when someone accesses your website, making sure they download quickly will help make your website load quickly

Caching

Use GZIP, caching and CDN’s
Cloudflare can be used to cache and free SSL

Developer Tools

Use free tools like Audits available in Chrome Developers tool (right click on a web page > Inspect or Ctrl + Shift + I) to analyze site performance and improve things.

Reviews

Product customer reviews provide valuable feedback and validation to other shoppers on your products and service.

Did I miss anything off this list? Please let me know and I will add it.

How to check a number is valid when a form is submitted to your PHP code?

You have a form on your website and you are collecting numbers

You want to make sure they are valid numbers.

How do you make sure they are valid numbers?

First, you can validate them client-side in the browser, before the form is submitted to your server

With HTML5 you can define the input field type as email and make it a required field, like this:

<input type="number" name="email" required>

Example of how the number input looks

The number input also supports a range of acceptable numbers, so if you only wanted to numbers between 1 and 10, you would set the min and max attribtues like this:

Example of how the number input with a range looks

<input type="number" min="1" max="10" name="number" required>

Note that most of the frequently used browsers will support the above functionality.

Validating the input client side is one thing, but you have to validate it on the server also.

You can use this PHP code, to make sure that submitted number is really valid:


// Grab the POSTed number input field
$number = $_POST['number'];
$number_range = $_POST['number_range'];

// Use filter_var to check if the number is valid
if (filter_var($number, FILTER_VALIDATE_INT) === false) {
echo("$number is not a valid number");
} else {
echo("$number is a valid number");
}

// Use filter_var to check if the number is valid and within the range
if (filter_var($number_range, FILTER_VALIDATE_INT, 1, 10) === false) {
echo("$number_range is not a valid number");
} else {
echo("$number_range is a valid number");
}

For a bare bones code sample, demonstrating the above you can find it below:

If you found this post helpful, please subscribe below for more.

How to check an email address is valid when a form is submitted to your PHP code?

How to check an email address is valid when a form is submitted to your PHP code?

You have a form on your website and you are collecting email addresses

You want to make sure they are valid email addresses, so that you can make use of them

Whether you are replying to a customer inquiry

Or using the email addresses for a marketing mailing list

How do you make sure they are valid email addresses?

First, you can validate them client-side in the browser, before the form is submitted to your server

With HTML5 you can define the input field type as email and make it a required field, like this:

<input type="email" name="email" required>

Note that most of the frequently used browsers will support the above functionality.

Then once your form is submitted you can use this PHP code, to make sure that submitted email address is really valid:


// Grab the POSTed email address input field
$email = $_POST['email'];

// Use filter_var to check if the email address is valid
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is not a valid email address");
} else {
echo("$email is a valid email address");
}

For a bare bones code sample, demonstrating the above you can find it below:

How to call a PHP function (with parentheses)

How to call a function in PHP

A reader of my blog recently emailed me, asking me to check over some PHP code

Nothing works from my php file except just connecting to the database

It’s simple code – I’m not doing anything fancy

So here’s the PHP code supplied:

function getConnection( ) {

$host="host";
$port=3306;
$socket="";
$user="me";
$password="mypassword";
$dbname="downloads";

@ $con = new mysqli($host, $user, $password, $dbname, $port, $socket);

if ( mysqli_connect_errno()) {
echo "Connection function failed";
return false;

} else {
echo "Connection function succeeded";
return $con;
}
}

$res = getConnection;
if (!$res) {
echo "Connection failed. " . mysql_errno($res) . ": " . mysql_error($res). "\n";
}
else {
echo "Connected to database." . "\n";
}

$key = md5(microtime());
if ($result = $res->query("SELECT count(*) FROM downloads WHERE downloadkey = '{$key}' LIMIT 1")){
echo "Select succeeded." . "\n";
}
else
{
echo "Select failed." . "\n";
}

They helpfully supplied output and the error message too:

Connected to database. Fatal error: Call to a member function query() on a non-object in /path-to/filename.php on line 33

Which seems to suggest to the connection is fine, but when it comes to use the connection. The connection object isn’t actually an object.

They are using a function to create the database connection, a good sign.

There are a few lines after the function, they all look okay

But wait, maybe something doesn’t look right about this line:

$res = getConnection;

Notice anything missing?

Does it look better like this?

$res = getConnection();

Yes! Calling a PHP function, even though that function has no parameters, you must include the parentheses!

Otherwise PHP doesn’t know it’s a function and actually assumes getConnection is a string. As demonstrated by this snippet:

$res = getConnection;
var_dump($res);
// Outputs: string(13) "getConnection"

So that was the first problem, the reader assumed the connection was being created.

When in fact the function was never being called.

Even though they have code to check the connection.

However, that code:

if (!$res) {

Was never going to equate to false, as $res was actually a string “getConnection”.

That if statement should be changed to this:

if (!is_object($res)) {

Now we are actually checking whether the $res variable is actually a connection object or not!

How to add a subscriber using MailChimps API with PHP

How to add a subscriber using MailChimps API v3.0 with PHP and CURL

A quick step-by-step guide with PHP code

Here was the problem, my greeting card website (PamitCards.ca) has a list of subscribers sitting in a MySQL database table. Whenever I wanted to use MailChimp to send the list of subscribers an email. I would have to export the email addresses as a CSV file. Then log-in to MailChimp, import the file so that any new subscribers would be added. MailChimp’s import process would then email me with a list of additions, bounced and un-subscribed email addresses. I would then take those and update the MySQL database table removing the redundant addresses.

Whoa that’s a lot of steps, quite a time consuming process for something that could be automated / integrated!

Realizing that using MailChimp’s API, I could add subscribers to my MailChimp list. Thereby making the above process redundant along with the database table. What’s the point of keeping that data if it’s in MailChimp.

So here’s how to make it work…
  1. If you are reading this, I’ll assume you already have a MailChimp account and at least one list set-up. If not it’s really easy to sign-up and get started with MailChimp.
  2. Then you will need an API key if you don’t have one already, find it under Account > Extras > API keys. Note that running the code locally under WAMP I had to change the https to http to make it work.
  3. Once your key is generated, you will use the last 3 characters as part of the API call, in my case it was us2 to make this url https://us2.api.mailchimp.com/3.0
  4. Then you will need to generate your Auth token, I used Postman which is available in the Chrome Web store to add to your browser.
  5. Using Basic Auth you can put in your Username and Password and this will generate a string that looks like this Basic cGFtaXRjYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXZGUwNS11czI=
  6. First do a GET call to http://us2.api.mailchimp.com/3.0/lists this will return a list of your lists, find your relevant list id to insert in the code below along with your API key
  7. Then specify an email address to Subscribe and run the code.
  8. You should get a response in the browser showing the the email address has been added
  9. You can extra fields if your list and signup process has them.
  10. Any problems, please let me know with a comment or follow me on Twitter for more helpful posts…
  11. Here’s the PHP code I used:

7 tips for using a standing up desk

Interested in getting a stand up desk?

If you are used to sitting at your desk, here are 7 tips to help you get started with a standing desk.

You can download a print ready PDF of the tips

  • Choose a desk with variable height, such as a Varidesk
  • Make sure you take breaks from standing
  • Wear flat shoes
  • Shift your body position / weight
  • Will your desk be able to support both your monitors?
  • Start your work day standing up
  • It may take a while to get used to it, as with anyting new, but keep using it

Read more about the reasons to get a stand up desk here

7 Advantages to using a standing up desk when working as a developer

Are you spending all your work day sitting writing code?

Is your back feeling stiff or causing you some pain?

Maybe it’s time to consider getting one of those new hip standing desks?

Here’s 7 reasons that might help convince you a standing desk is worth it.

You can always try one out with just cardboard boxes…

Also check out the link at the bottom to download a print ready PDF of the advantages

7 Advantages FOR STAND UP DESKS
Download as a PDF – 7 Advantages for stand up desks

How do you sit and code for so damn long all day, every day?

How do you sit and code for so damn long?

I feel like my wrists are going to snap off and my back/neck is deforming.

Your day goes something like this, as it does for a lot of people…

  • Wake up…
  • SIT in your car and drive to work
  • Or SIT maybe stand on public transport work
  • Get to the office and SIT down
  • Go for a coffee break and SIT down
  • SIT back down at your desk
  • Eat lunch SITTING down
  • SIT back down at your desk
  • Head home probably SITTING down
  • Get home and SIT down to watch some TV / Do more work / Eat
  • Repeat 5 day a week.

Sitting all day is harmful to your health, and you can’t fix it by exercising.

So what’s the answer if it’s not exercising?

Sounds obvious, but it’s trying to sit less…

That’s easy to say except when your paid to SIT for your day job…

What you need is a variable height stand up desk!

After years of development sitting down and enduring back pain I decided to get one.

I didn’t want to spend the money on a piece of office furniture it and it wasn’t covered by medical insurance.

My company wasn’t going to pay for it.

You might be lucky enough to work for a company that will do.

At the end of the day I decided a few hundred dollars for a standning desk versus back pain was a no brainer!

I wanted to live without the pain.

We have standing desks, the first couple of weeks were hell though.

And yes after years of sitting, to be standing at your desk, does hurt, it’s not easy.

But you do get used to it.

You stand sometimes and you sit sometimes as opposed to sitting all day.

I start the day off standing up and as the day goes by end up sitting more.

Sitting every so often, good shoes and a padded mat also make a big difference.

I find flat heeled shoes help for standing and working at the desk.

You’r standing in place, sure, but you aren’t usually as immobile as you would be if you were sitting. You shift your weight around, you’re also more inclined to walk away from your desk.

I switched to a standing desk a few months ago. Over the first month, the back pain decreased until it vanished completely.

For more healthy tips, please subscribe below…