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.

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 access PHP session variables from another PHP page

​​

One of my subscribers sent me an email asking me about problems he was having with sessions.

He had already created a session variable in one PHP file.

Now he had a second PHP and wanted to access the session variable in it.

However he was struggling to access his session variable.

He found the only way to access it, was by including the first PHP file in the second PHP file.

This is a common problem which seems extremely frustrating.

A session and it’s variables should be shared with all the PHP pages in your project right?

The session is, but you need to know how to access the session and it’s variables in another PHP page.

So I asked him if he had called the PHP function session_start()

Calling this function is necessary in every PHP page where you want to use a session variable.

The session_start() function will either resume an existing PHP session or start a new one if there isn’t one existing already.

He responded back to me after updating his php code with the call to the session_start() function.

After updating his code he was able to access his session variable in his second PHP page, without including the first PHP file.

So every time you need to access a PHP session variable don’t forget you need to call session_start() first.

If this post helped you please subscribe and save yourself more development time with my helpful PHP web development tips delivered to your inbox weekly.

How to use PDO to UPDATE data in MySQL using PHP

You need to get data safely updated from a web page to a MySQL table in your database

You need to sanitize that data from user input and protect against SQL injections.

The following simple example will show you how to accomplish that.

These are the ingredients you will need:

  1. A MySQL database
  2. A table to store the data in the above database
  3. The credentials to above (the host location, username and password)
  4. Which you can use to create a connection in your PHP page
  5. A form with fields to input the data
  6. A way to sanitize the data
  7. Safely update the data

What if you don’t have all of the above set-up?

Don’t worry at the end will be a link to example PHP source code along with the SQL statements to create the database and table.

PHP PDO (PHP Data Objects) makes it very easy to UPDATE data from your table.

First, to connect to the database with PDO is very simple:

$dbh = new PDO('mysql:host=localhost;dbname='. $db_name, $db_username, $db_password);

The above line creates a connection and stores it in the $dbh variable as an object

That variable can then be used to save the data using an UPDATE statement:

$stmt = $dbh->prepare('UPDATE makes SET make = :make WHERE id = :id');

This prepares a statement which we can then bind the make parameters safely too, protecting against SQL injections.

We use PHP’s filer_input() function to santize the data coming from the input fields POSTed to the server from our form:

$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
and
$make = filter_input(INPUT_POST, 'make', FILTER_SANITIZE_STRING);
Then using the bindParam() function we can bind the $id variable into the statement:
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

Then the $make variable can also be bound to the prepared statement:

$stmt->bindParam(':make', $make, PDO::PARAM_STR);

Then the statement is executed to run the prepared SQL statement, resulting in the record being updated in the table:

$stmt->execute()

These are the key lines to connect to the database. Sanitize the data and UPDATE the data in the database.

Of course the above code lines don’t show the HTML need to make the form and input fields.

You can find that here on github as a simple PHP PDO CRUD Demo. Please download / fork the code and try it out.

The demo is a simple CRUD example of using PHP, PDO and MySQL to display a list of car makes

This post is a part of a series, you can read more about viewing the data with PDO here

How to use PDO to DELETE data from MySQL using PHP

You need to delete data safely from a web page and your MySQL table in your database

You need to sanitize that data from user input and protect against SQL injections.

The following simple example will show you how to accomplish that.

These are the ingredients you will need:

  1. A MySQL database
  2. A table to store the data in the above database
  3. The credentials to above (the host location, username and password)
  4. Which you can use to create a connection in your PHP page
  5. A list of records displaying your data
  6. A way to select and delete a record
  7. Safely delete the data

What if you don’t have all of the above set-up?

Don’t worry at the end will be a link to example PHP source code along with the SQL statements to create the database and table.

PHP PDO (PHP Data Objects) makes it very easy to DELETE data from your table.

First, to connect to the database with PDO is very simple:

$dbh = new PDO('mysql:host=localhost;dbname='. $db_name, $db_username, $db_password);

The above line creates a connection and stores it in the $dbh variable as an object

That variable can then be used to delete the data using a DELETE statement:

$stmt = $dbh->prepare('DELETE FROM makes WHERE id = :id');

This prepares a statement which we can then bind the id parameter safely too, protecting against SQL injections.

We use PHP’s filer_input() function to santize the data and make sure it’s an integer. The GET parameter comes from the query string in the URL of the delete.php page:

$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);

The $id variable can then be bound to the prepared statement:

$stmt->bindParam(':id', $id, PDO::PARAM_INT);

Then the statement is executed to run the prepared SQL statement, resulting in the record being deleted from the MySQL database table:

$stmt->execute()

These are the key lines to connect to the database. Sanitize the query string variable and DELETE the record in the database.

Of course the above doesn’t show the HTML need to make the form and input field.

You can find that here, on github as a simple PHP PDO CRUD Demo. Please download / fork the code and try it out.

The demo is a simple CRUD example of using PHP, PDO and MySQL to display a list of car makes

This post is a part of a series, you can read more about viewing the data with PDO here. Which generates the delete link to delete.php

How to use PDO to INSERT data into MySQL using PHP

You need to get data safely from a web page to a MySQL table in your database

You need to sanitize that data from user input and protect against SQL injections.

The following simple example will show you how to accomplish that.

These are the ingredients you will need:

  1. A MySQL database
  2. A table to store the data in the above database
  3. The credentials to above (the host location, username and password)
  4. Which you can use to create a connection in your PHP page
  5. A form with fields to input the data
  6. A way to sanitize the data
  7. Safely insert the data

What if you don’t have all of the above set-up?

Don’t worry at the end will be a link to example PHP source code along with the SQL statements to create the database and table.

PHP PDO (PHP Data Objects) makes it very easy to INSERT data from your table.

First, to connect to the database with PDO is very simple:

$dbh = new PDO('mysql:host=localhost;dbname='. $db_name, $db_username, $db_password);

The above line creates a connection and stores it in the $dbh variable as an object

That variable can then be used to save the data using an INSERT statement:

$stmt = $dbh->prepare("INSERT INTO makes (make) VALUES (:make)");

This prepares a statement which we can then bind the make parameter safely too, protecting against SQL injections.

We use PHP’s filer_input() function to santize the data coming from the input field POSTed to the server from our form:

$make = filter_input(INPUT_POST, 'make', FILTER_SANITIZE_STRING);

The $make variable can then be bound to the prepared statement:

$stmt->bindParam(':make', $make, PDO::PARAM_STR);

Then the statement is executed to run the prepared SQL statement, resulting in the record being added to the table:

$stmt->execute()

These are the key lines to connect to the database. Sanitize the data and INSERT in the database.

Of course the above doesn’t show the HTML need to make the form and input field.

You can find that here though on github as a simple PHP PDO CRUD Demo. Please download / fork the code and try it out.

The demo is a simple CRUD example of using PHP, PDO and MySQL to display a list of car makes

This post is a part of a series, you can read more about viewing the data with PDO here

How to use PDO to SELECT data from MySQL using PHP example

You have a MySQL table of data in your database, you want to display it on a webpage, so it can be displayed and viewed by other people.

You need to have a few things in order to accomplish this:

  1. A MySQL database
  2. A table containing data in the above database
  3. The credentials to above (the host location, username and password)
  4. Which you can use to create a connection in your PHP page
  5. A way to iterate through the records so they can be echoed out
  6. The table field names so we can display them on the page

What if you don’t have all of the above set-up?

Don’t worry at the end will be a link to some example PHP source code along with the SQL statements to create the database and table.

PHP PDO (PHP Data Objects) makes it very easy to SELECT data from your table.

To connect to the database with PDO is very simple:

$dbh = new PDO('mysql:host=localhost;dbname='. $db_name, $db_username, $db_password);

The above line creates a connection and stores it in the $dbh variable as an object

That variable can then be used to retrieve the records using a SELECT statement:

foreach($dbh->query('SELECT * FROM makes ORDER BY make ASC') as $row) {

This allows us to use the resulting rows of data returned by the query.

Using the field names from the database table, we can output the data with an echo statement:

echo "<td>". $row['make'] ."</td>";

After we’ve finished, set the variable to null to free up the connection:

$dbh = null;

So with the above few lines of code, we can connect to the database. Retrieve the data and output it.

To make everything look good, we need a few more lines of code to create a table.

The full source code is available here on github as a simple PHP PDO Crud Demo.

The demo is a simple CRUD example of using PHP, PDO and MySQL to display a list of car makes

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!