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.

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 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 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 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…