How to Build a Website: - Étoile Web Design

Presents
How to Build a Website:
A guide to understanding the technologies
that make up the modern internet.
1 - Introduction
2 - Domains/Hosting
3 - HTML
4 - CSS
5 - PHP
6 - MySQL
7 - Javascript/JQuery
8 - Conclusion
В© Г‰toile Web Design, 2012.
Page 1
Introduction
A web design company would have to be crazy to write an e-book on how to build a website on your
own, wouldn’t it? It might surprise you to learn that one of the big challenges faces companies that
offer web design and other digital products, such as phone apps, is explaining to current and potential
clients exactly what they do.
Imagine if you were looking to buy a new home or renovate the one you’re living in now. If you didn’t
know how anything about how a house worked, how would you be able to tell a quality contractor from
someone who will deliver a product which will be falling apart in a couple of years? If you deliver a
quality product, you want as many people as possible to understand how it works to be better able to
set you apart from competitors who have a lower quality offering. For that reason, we think that the
best kind of client is an informed one.
Sticking with our home analogy, there are plenty of do-it-yourself’ers willing to undertake a renovation
of their home or business with only the help of a couple of friends and the words of wisdom of the sales
person working at the hardware store. On the other hand, there are just as many people who would
rather leave the work to a professional, and be sure of getting a quality product that will last.
With those two groups in mind, we’ve split most of the chapters in the book into two parts. The
introduction, chapter 2 on domains and hosting, and the conclusion are for everyone. For chapters 3-7,
the first part of the chapter is for everyone: it covers why some aspect of a webpage is necessary, and
the history. The second part is geared to the DIY crowd: it covers the details of how to actually add in
that portion of the webpage. Taking advantage of the e-book format, we’ll be switching to grey text for
the DIY parts and putting in links to skip to the next non-DIY portion.
Building a website is actually pretty simple, the kind of thing that can easily be learned in a semester
long university course. Almost every website you’ll ever browse is made up of, at most, 5 parts. Almost
all of them use Hypertext Markup Language (HTML), Cascading Stylesheets (CSS), a server-side language
like Hypertext Preprocessor (PHP), javascript in a visitor’s web browser, and a database language like
MySQL to store and retrieve data. We’ll cover all five of those parts in detail, in chapters 3-7 of this
book, but it makes sense to give a short overview of each in the introduction so that you get a sense of
the big picture.
The most essential part of any website is the HTML code, the backbone of how websites show up in your
web browser. HTML stands for hypertext markup language, and is made up of “tags” which “markup”
plain text to give it some structure. These tags are meant to be used only to show how the data in a
page should be organized, not to describe any of the fonts, colors, borders, etc. that decorate most
sites. The tags can be hierarchical in nature: imagine a list and then the items in that list. They can also
be parallel, like an image side by side with text. Tags are “nested” within each other, like a sentence
being part of a paragraph, which is part of a page, which is then part of a book. HTML is the framework
that sites were originally built with when the first internet browsers were created in the early 1990’s.
В© Г‰toile Web Design, 2012.
Page 2
If you want to create more than just plain text pages, you’re going to need to incorporate some CSS.
Where HTML tells your web browser about the structure of the data that makes up a web page, CSS tells
your browser how that data should be laid out and presented. If you want to change the colors, text
fonts and styles, or layout of a page, then CSS is what you’re going to need. The basic idea behind CSS is
that styles “cascade” from parent elements to any child element nested within them. Using the book
analogy, if your CSS code says that a page of the book will have red text, then every paragraph on that
page will automatically have red text. You could then go on to specify with further code that one of the
paragraphs should have purple text, without changing the color of the text in the other paragraphs. CSS
lets you change the style of an entire site from one document, which solved in important problem that
developed as websites became more complex in the mid 1990’s.
Once you want to have dynamic content included on your site, the best way to deal with that is using
PHP. Static pages using only HTML and CSS were what visitors expected 5 or 10 years ago when they
visited a small business site. Today though, dynamic content like new product details, seasonal menus
and upcoming events are the kind of content which grabs a visitor’s attention. The best way to add
those “must-have” features is by using PHP, which runs on the web server before any information is
transmitted to your visitors’ browsers. While it is the most challenging to learn, you can use PHP to do
pretty much anything you can imagine with your website.
As a business’ website gets more complex, one of the most requested features is storing a visitor’s
preferences for language, font-size, previous product purchases, etc. between visits. Using MySQL, you
can store data either to help make visiting your site more enjoyable for your visitors, or to help you
understand how your visitors are using your site. MySQL is a database language, with features that fall
somewhere between those available in Microsoft Access and those available in Oracle Database. It is a
must for letting visitors login to restricted access pages or if you want to offer premium content only to
paid subscribers.
Last but not least, Javascript is what you want to use if there are any actions that need to be completed
between page loads. One of the most common examples of Javascript in action are the rotating set of
pictures, or image sliders, on the front page of many websites. Another great example is forms that have
fields which need to be filled out a certain way before they can send, such as telephone or postal code
fields. Javascript runs in a visitor’s browser, so as a developer, you have a little less control over it. We’re
also going to cover JQuery, a popular library that extends the functionality of Javascript, while at the
same time also making it easier to use.
There are a number of examples and sample bits of code spaced out throughout the book, all of which
are available through the booksite at http://www.etoilewebdesign.com/how-to-build-a-website-ebook/.While it can sometimes be helpful to write out the code yourself, if you’re getting an unexpected
error you can always download the files from there. There is also a link to our blog with tips for small
business owners on how to effectively use a website, social media and in-depth tutorials that go beyond
the scope of this book, so be sure to check it out!
В© Г‰toile Web Design, 2012.
Page 3
Domains & Hosting
Before you start building your own website, you'll need to get a domain name and a web hosting
provider. A domain name is the address that you type into the address bar to visit a site. It will be the
name that you give out to customers, so be sure to choose it carefully. Domain names can be purchased
from the hosting provider you decide to go with. Deciding on a web hosting provider can be a
complicated decision as well. There are some very cheap hosting providers which you can find online,
but sometimes it's worth paying a few dollars per month to ensure reliable service and responsive
customer support. Since the quality of a hosting service can change quickly when a hosting company is
bought by another company, we won't be recommending one in this e-book (in case the company we
suggest gets bought). Instead, you can check the book site to get our most up-to-date hosting
recommendation.
There are a number of things to consider when selecting a domain name. First, it should reflect your
business or the service you provide. If your business is housekeeping, then a web address
like www.freshflowers.com could be confusing for your visitors. Second, your domain name should be
easy enough to remember. Sticking with a housekeeping business, a name
like www.housekeeping9514.com might be housekeeping themed, but unless 9514 was easy for your
customers to remember for some reason, it could be difficult for them to remember after they come
home. Finally, it's a good idea to keep a domain name short. Three words long, something
like www.thehousekeepinggroup.com, is probably as long as you want to get. Even if it represents your
service, www.thebesthousekeepinggroupintown.com is long enough that many people would forget a
word, type it incorrectly, or make any of a dozen other mistakes while trying to reach your site.
When it comes to web hosting, it makes sense to start the discussion with what it is exactly. So what is
web hosting? Web hosting companies are the connection between an individual or company and
internet visitors. To put a webpage online, you’ve got to go through a web host. You or your website
developer will upload all of the necessary files to the web host according to the company's guidelines
and policies, and based on the languages used to create the site. The files are uploaded to the web
hosts' server, where they're available for anyone with an internet connection to browse.
When choosing a web host, it's important to keep your personal or corporate goals in mind. If it's your
own personal website, you might not mind if the web host puts banner ads on it. However, if it's a
corporate site you're preparing, do you want your web host to advertise similar businesses on your
page? Some web hosts offer free web hosting services if the company is allowed to place advertising on
it or charge a small fee to keep it clear of outside sponsors. For most businesses, it’s a good idea to
spend about $10/month in order to have complete control over everything that is or isn't on their site.
Last but not least, it's usually a good idea to inquire upfront about a web hosting company's site transfer
policy. If a company is offering you a great deal on your first year of web hosting, are you going to be
locked in with them for years because you're unable to move your site afterwards? Most of the time, it
makes sense to pick a host who is upfront about long term costs, because changing hosting providers
can be a big hassle, especially for those with a limited technical background.
В© Г‰toile Web Design, 2012.
Page 4
HTML Chapter
HTML is the backbone of almost every website, from those created in the early 1990's right up to today.
HTML consists of tags, and anything that comes between an opening tag and a closing tag is part of that
“element”. A good way to think about HTML structure is to imagine a lot of containers, some big, some
small. If you're looking to store things, you would put down a large bin to start with, then put in some
medium sized bins, before finally putting small bins in. A small bin might be put directly into the large
bin, or a number of them could be contained within a medium sized bin within the large bin. It all
depends on what you’re trying to do!
Almost every page you visit on the internet starts with an "<html>" opening tag and ends with an
"</html>" closing tag, meaning that everything in a page is part the html element, which was the large
bin in our real world example. There are hundreds of tags that can be used in an html document, some
of which contain a lot of other tags within them and some of which only containing an image or some
text. Some tags are more common than others, and we'll cover about a dozen of the most common ones
later in this chapter.
The simplest website possible would be created with the following structure (Sample 1.1):
<html>
<body>
Website Text
</body>
</html>
which would look something like this when displayed in a web browser:
Most people would agree that the internet would not be very popular if it was filled with pages that
looked like the one above. The basic idea behind HTML, though, is apparent even in such a simple
document. The opening "<html>" tag tells the browser that the HTML element (otherwise known as a
web page) is beginning. The "<body>" tag starts the portion of the page which is actually displayed
within the web browser. The words "Website Text" are displayed within the browser because they are
within the "body" of the page. The last two tags, the "</body>" and "</html>" tags, close the elements.
Any tag with a forward slash ("/") right after the opening less than ("<") character is a closing tag, and
any tag without a forward slash is an opening tag.
В© Г‰toile Web Design, 2012.
Page 5
Let's take a look at a slightly more complicated document structure (Sample 1.2):
<html>
<head>
<title>Website Title</title>
</head>
<body>
<p>Paragraph One</p>
<p>Paragraph Two</p>
<p>Paragraph Three</p>
</body>
</html>
which would look like this when displayed in a web browser:
Already this slightly more complicated code makes for a more interesting page. Let's cover what changes
between the two documents: first there's a new "<head>" section, which contains a "<title>" element,
which isn't displayed in the browser. Instead, if you look at the title bar in your browser, you’ll see that
your page now has a title. The "<head>" of the document passes information to the browser which isn't
displayed directly on the page, but which is related to the content of the page. Things like the page's
title, the stylesheet (covered in the next chapter) which will help to make the page more interesting
graphically, and Javascript (covered in chapter 7) which is associated with the page.
Second, there are now three paragraphs in the body of the document, denoted by the "<p>" tags. These
paragraphs automatically start on new lines, and are spaced out with a certain amount of white space
between thems, helping to give structure to the content. Already, you can imagine using just the half
dozen tags we've covered to create a web page that looked something like a book.
Skip to next non-DIY section
Hopefully by this point, the concept of large containers holding smaller containers that HTML is based
on is starting to become clear. Some of the other commonly used tags in HTML are:
- Divisions (<div>) and Sections (<section>): Used as a generic ways to divide up content. For example, in
a two column page layout you could have one section for the right side of the page and one section for
the left side of the page.
- Headings (<h1>, <h2>, <h3>, <h4>, <h5> and <h6>): Used to make the title or subtitle stand out from
the rest of the content. The importance of the heading, and the font size assigned to it, is greatest for
В© Г‰toile Web Design, 2012.
Page 6
<h1> tags and decreases down to <h6> tags, which usually display not much larger than regular text.
Heading tags are automatically put on their own lines, with space above and below them, making them
stand out from regular text.
- Ordered lists (<ol>), Unordered lists (<ul>), and List items (<li>): Ordered and unordered lists are used
to create lists of items, which either have a specific order in the case of ordered list or are in any random
order in the case of unordered lists. A list consists of an opening tag (<ol> or <ul>), as many list items
as necessary (each one starts with an <li> tag and ends with a </li> tag), and then a closing tag (</ol> or
</ul>, same as the opening tag). You can imagine a recipe having both kinds of lists in it. The instructions
would be an ordered list, because you need to follow them in the order that they're written, while the
list of ingredients would be an unordered list, because you can gather them in any order you'd like.
- Anchors (<a>): Used to create links to other pages. The anchor tag uses what is known as an
"attribute", or additional text within the tag, to define where the link should take a user when it is
clicked. The attribute that tells the browser where to go is the "href" attribute. To link to the google
search homepage, for example, you could have a tag that looked like:
<a href="http://www.google.com">Text that links</a>
- Image tags (<img />): Used to add an image to a page. They take an attribute as well, the "src"
attribute, which tells the browser where the image that is to be displayed is located. Unlike most other
HTML tags, there is no closing tag for image elements. Instead of the closing tag, a forward slash is used
before the closing greater than (">") character. A typical img tag would look like:
<img src="http://www.etoilewebdesign.com /EWD_241012_Screenshot.png" />
The final aspect of HTML we'll cover in this chapter will be selectors. Selectors make modifying the
presentation of an HTML document with CSS more precise, and there are two types of them. The first
type is the 'id' attribute. Each id should be unique to one element on a page; there should never be two
elements with the same id attribute on the same page if you’re using the id attribute correctly. Often,
developers use a numbering system to ensure that the id for each element is unique. For example, if we
were giving an id to a couple of sections, we could make it something like:
<section id='large-column-1'></section>
<section id='large-column-2'></section>
By adding the number to the end of the element's id, we ensure that it is unique to that element, which
is the golden rule for element id's. The second type of selector is the 'class' selector. Classes can be
repeated for multiple elements, whether they are of the same type or different types, though it often
makes sense for a class to refer to one type of element. By combining classes and id's, you can take two
elements and repeat some of the same aspects, while adding small differences between the two. We'll
see why class and id selectors are useful in the next section.
Skip to next non-DIY section
В© Г‰toile Web Design, 2012.
Page 7
Before moving on to the next chapter, we'll put everything that we've covered about HTML together
into the example below (Sample 1.3):
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<section class=”smallColumn” id=”leftColumn”>
<h2>Interesting Links</h2>
<ul>
<li><a href="http://www.google.com">Great Search</a></li>
<li><a href="http://www.etoilewebdesign.com">Great Web Development</a></li>
<li><a href="http://www.allrecipes.com">Great Recipes</a></li>
</ul>
</section>
<section class=”largeColumn” id=”rightColumn”>
<div>
<h1>Simple Web Design</h1>
<p>To design a simple website, all you need is a basic understanding of HTML tags, and how to put them
together.</p>
</div>
<div>
<h1>Complicated Web Design</h1>
<p>To design a more complicated website, you need to be able to add a cascading style sheet to edit the
presentation, PHP to process web forms, MySQL to store information sent in by your users, and
javascript to check information being sent by your users.</p>
</div>
</section>
</body>
</html>
В© Г‰toile Web Design, 2012.
Page 8
which looks like this in a browser:
We will be referencing that final example as we continue on through the rest of the chapters of this
book, so it might make sense to copy it down into a document of your own. Feel free to edit it, save it as
an .html file, and open it in your web browser to see what the code you add looks like!
В© Г‰toile Web Design, 2012.
Page 9
CSS Chapter
Whereas HTML is only focused on the structure of a document, CSS focuses exclusively on the
document’s presentation. CSS was created in the mid 1990’s as a solution to a growing problem. Web
developers wanted to standardize the look of websites, by passing instructions for presentation of those
sites to the web browsers of visitors. New HTML tags were created to alter the presentation of a page,
such as the <font> tag which allows for a different font to be used within the tags, the <u> tag which
underlines the text between the tags, or the bgcolor attribute which changed the background color of
an element.
Problems started to arise as websites grew larger and more complicated. If a company decided to
change the design of their site, every single page had to be updated to the new color scheme, font styles
and sizes. On a large site or one with lots of pages, such as a newspaper’s archive, it was a long and
expensive process. CSS was created so that styles would only have to be changed in one place to take
effect on the entire site.
The basic idea behind CSS is to assign style attributes to different elements, based on what the element
is. This is done by selecting a certain element, then using name/value pairs for the different attributes
that need to be altered. It’s probably easier to understand by looking at an example, so let’s start with
the simple one below:
div {
background:blue;
color:orange;
}
In the example above, we’re telling the browser to display all of the div’s in a document with a blue
background color and orange text color. The spacing in the text is not important. The whole thing could
be written on one line, but it’s easier to understand by placing the element selector and opening bracket
on the first line, as many attribute name/value pairs as required each on their own subsequent line, and
then the closing bracket on the final line. The last thing that we need to do for the changes to take effect
is to include them within the <head> section of the HTML document we created in the previous chapter.
We also need to tell the browser that this is styling information, by enclosing it in <style> tags. The final
product looks like this (Sample 2.1):
<style type="text/css">
div {
background:blue;
color:orange;
}
</style>
В© Г‰toile Web Design, 2012.
Page 10
Notice that the “type” attribute is set to “text/css”, so that the browser knows that the style information
is in CSS form. You can take that little bit of CSS above and add it to the <head> portion of the HTML
example from the end of the last chapter, right after the opening <head> tag. If you view it in your
browser, the result should look something like this:
Up to this point, using CSS would save you a bit of time if you’d like to change the layout of your site,
since all of the presentation information is in one place. You would still need to go through each page of
your site though to make the changes for that page. To really start to save time, we need a way to
include the same information on every page. That way we’d only have to makes changes once, and they
would appear on every page. To do that, instead of putting the style information directly on the page,
we’re going to include it from another file. Create a file called styles.css, add the style information for
the <div> elements that we just created, and save it in the same folder as your HTML example file. Now,
remove the style information in the <head> section of your HTML document and replace it with the line
below:
<link rel="stylesheet" type="text/css" href="styles.css" />
This above tells the web browser that there’s important information linked to the HTML document, that
the relationship (rel) of the information to the document is that of a stylesheet, that it’s in CSS form, and
that the hypertext reference (href), or source of the information, is in a file called “styles.css”. Now we
can include that line in any new pages that we create, and when we make changes to the styles.css file,
the changes will take effect on the entire site.
Now that you understand how to include a CSS file with an HTML document, the next step is learning
how to select elemnts. There are a number of different ways to select an element before altering its
attributes. Add the following code to your CSS file:
.smallColumn {
width: 300px;
}
section.largeColumn {
В© Г‰toile Web Design, 2012.
Page 11
width: 600px;
}
#leftColumn {
height:400px;
}
There are a couple of things to discover in the above code. First, in CSS you use a period (“.”) followed by
a class name to select all elements of a certain class like we do with “.smallColumn”. Second, when you
put the type of element you’d like to select first and then include the period and the class name, you’re
able to select only elements of a certain type of that class like we do with “section.largeColumn”. In the
example above, we specify that only sections which have a class largeColumn, and not any other
elements which might have the class largeColumn, should be selected. Third, when you start a selection
with a hash sign (“#”) in CSS, followed by an id name, you select only the element(s) with that id as an
attribute, like we do with “#leftColumn”.
The reason that cascading stylesheets have the name “cascading” is because the more specific selector
always gets priority when there is a conflict. For example, let’s say that there was a an element that had
an opening tag that looked like this:
<div class=”small” id=”big”>
In our imaginary CSS file, let’s pretend that this was written:
div {
width:400px;
}
.small {
width:200px;
}
#big {
width:600px;
}
In this case, the element is a of the type div, so initially it should have a width of 400px, right? Well, class
is more specific than the type of an element, so that width is set to 200px next. Finally, id is the most
specific of all, since there should only be one element with a specific id within a document, so the
element is set to 600px. The idea of the cascade is that you can set certain attributes for all div
elements, change a few of them for a specific class, and then change the same or other attributes for an
element with a certain id. In that way, the attributes for a certain element “cascade” through until they
reach the most specific selector.
Skip to next non-DIY section
В© Г‰toile Web Design, 2012.
Page 12
The final concept that is needed to understand how to use CSS effectively is the “Box Model”. CSS treats
each element as a box of a certain size, with layers that you can specify independently. The diagram
below shows the basic concept:
The content is at the center, surrounded by its padding, then its border, and finally by its margin. By
default in most browsers, the padding, border, and margin of an element have no size, so for them to be
visible, they need to be given a size inside the CSS file.
Finally, let’s take a look at some of the more common attributes that you can use to change the
presentation of your document:
-
-
-
background: Let’s you select a background color for the element. The easiest way to pass that
along is by using the name of a common color (red, green, blue, etc.). You can also pass the
color information using an rgb number (three numbers between 0 and 255, the first one is the
amount of red, the second the amount of green, and the third the amount of blue) or as three
pairs of hexadecimal numbers (more difficult to explain, but each pair again corresponds to the
amount of red, green and blue in the background from 00 to FF).
color: Let’s you select the text color within an element. You can pass the information along as
either the name of a common color, an rgb number of a hexadecimal string.
font: Can be used to change almost everything about an element’s font. From the size of it
(usually in pixels), to the type of font (arial, calibri, sans-serif, etc.) to the style of the font (bold,
italic, regular, etc.).
position: Used to change the layout of a page. The most commonly used values for the position
attribute are “absolute” and “relative”. Absolute positioning means that any positioning
instructions are expressed from the top-left corner of the parent element. Relative positioning
means that positioning instructions are relative to where the element would normally be
positioned.
В© Г‰toile Web Design, 2012.
Page 13
-
-
-
-
-
-
top and left: Used to change the position of an element. The two most common ways to
position an element, whether it’s being positioned relative or absolute. Both of these attributes
can take either a number of pixels (px) or a certain percentage (%) to alter an element’s
position. The number of pixels can be any number, even if the element ends up positioned
outside of its parent element. You can do the same with a percentage, by using a percentage
larger than 100%, since percentage is based on the size of the parent element.
float: The float property is one that can be difficult to master. Elements can float left, right or
none. If an element is floating left or right, it leaves the area not covered by an element free.
Text and other elements will wrap around an image with the float property applied to it, much
like in a magazine layout. Images are just one of the many use cases for the float property: we
can also achieve the popular two-column layout using floats. In fact, you can float just about any
element in your HTML.
width and height: Used to give an element the correct size. These can be set as a number of
pixels or as a certain percentage of the size of the parent element, similar to top and left.
margin and padding: Used to separate elements. They can be set as a certain number of pixels
or as a percentage of the size of the parent element. The difference between the two is that the
background of an element covers all of the padding area, while it does not cover the area taken
up by an element’s margin (see box model diagram).
border: Used to give elements distinct areas. The border of an element comes between the
padding and the margin of it. There are three sub-attributes to the border of an element, which
are the width of the border (in pixels), the style of the border (usually solid or dashed, but many
options), and the color of the border (using one of the three standard color options).
border-radius: Used to curve the corners of elements, the border-radius attribute was recently
added. It’s specified as the number of pixels from the corner of an element where the curving
starts to occur.
display: Used to change how elements are appear in the flow of a document. Display is often
used to hide an element. The default setting is “inline”, or display normally. It can be set to
“block”, which makes the element display similar to a headline or paragraph, set to “none”,
which means the element won’t be displayed at all, or about a dozen other less used settings.
To close out this chapter, we’re going to create the CSS file that we’ll be using for the remainder of this
document. You can either copy the text below, or get the complete file from the book site. Feel free to
makes changes and see how they alter the appearance of the HTML document we created in chapter 3
(Sample 2.2).
div {
float:left;
width:200px;
background: rgb(220, 220, 220);
color: rgb(90, 90, 110);
margin:10px;
В© Г‰toile Web Design, 2012.
Page 14
padding:10px;
border: 2px solid rgb(0,0,0);
border-radius:8px;
}
ul {
float:left;
width:180px;
list-style:none;
display:block;
margin:10px;
}
.smallColumn {
float:left;
width:350px;
}
. largeColumn {
float:left;
width:600px;
}
h1 {
color:rgb(255, 100, 0);
}
h2 {
color:rgb(00,60, 255);
}
Making our HTML document look like:
В© Г‰toile Web Design, 2012.
Page 15
PHP Chapter
Up until now, there have been almost no alternatives to the languages being covered. If you want to
build a web page that will be viewed by web browsers, you pretty much have to use HTML. If you want
to style the presentation of a site, you have no choice but to use CSS. When it comes to PHP though,
there are a number of alternatives such as Ruby, ASP and JSP. These are all server-side languages, which
means that they run on the web server and only the results are sent to a visitor’s web browser, not the
code itself. The reason that this e-book will cover PHP instead of any of the other options is simply
because it is the most widely used, with it being the server-side language used in almost 80% of sites
that use server-side code.
While HTML and CSS are used in pretty much every site you'll visit on the internet, about a quarter of
sites online use no server-side language at all. They are some of the most simple sites, without contact
forms, newsletter sign up forms, member sections or any other data being saved for a future visit or
sent to site administrator. We're going to cover a very, very small portion of PHP, just enough to give
you a taste of what it can do and hopefully a feeling about where it's appropriate to be using a serverside language in general.
To get started with PHP, you need a file name that ends in .php. If you're browsing online sometime,
keep an eye on the address bar, and you can get an idea of which pages are running PHP. There are
ways to run PHP without having the .php extension, but most of the time it is a good indication. Another
caveat that should be mentioned is that PHP won't work if you're trying to open a file on your own
computer with a web browser. This is because PHP runs on the host’s server not in web browsers. You
can visit the e-book site to see what the example code looks like when it's actually being run.
Most of the time with PHP, only a small portion of the code is actually PHP code, while the rest of it is
HTML. To tell the server to that you're going to be adding a PHP portion to the document, you start with
a PHP opening tag (<?php), and once you're done with a PHP portion, you finish with a PHP closing tag
(?>). Like other programming languages, PHP uses variables. If you've never seen a variable before,
they're a lot like the variables you learned about in your high school algebra class. Variables usually
store one of three kinds of information: numbers, text strings, or booleans (true or false variables).
Variables start with a dollar sign ("$"), and can have pretty much any name. Finally, each command that
is being sent to the server needs to end with a semi-colon (";").
Skip to next non-DIY section
We'll start with a bit of code that's not all that useful, but that easy to understand (Sample 3.1):
<?php
$firstVariable = "This is some text.";
$secondVariable = 451;
$thirdVariable = 9;
$total = $secondVariable + $thirdVariable;
В© Г‰toile Web Design, 2012.
Page 16
echo $firstVariable;
echo "This is a number ";
echo $total;
?>
Which, when run on a server outputs:
There are quite a few parts to understand about the above code. First, we're declaring three variables in
the first three lines of code. We set the value of the variable "$firstVariable" to "This is some text.", the
value of "$secondVariable" to 451, and the value of "$thirdVariable" to 9. Second, we do a bit of
arithmetic with the two variables that have numbers stored in them by setting the value of a new
variable, "$total", to the sum of "$firstVariable" and "$secondVariable", equaling 460. Finally, we use
the "echo" command to output the contents of the variables. The echo command simply outputs
whatever follows the command to the web browser. We output two variables as well as a random string
using the echo command, and since echo just outputs exactly the information passed on to it, the three
commands all appear on the same line.
While the above example might be helpful for explaining some of the basic concepts of PHP, the same
result could be achieved, and much more easily, but simple typing the word that are being output into
an HTML document. The real power of PHP is its ability to create dynamic content in websites. Before
moving on to the next chapter, we're going to add to the HTML document that we created in chapter 3.
After the closing tag for the heading that says "Complicated Web Design" in that document, add the
following line (Sample 3.2):
<?php
echo "We're using PHP to display the current server time, which is: ";
echo time();
?>
В© Г‰toile Web Design, 2012.
Page 17
Which should look like this, when run on a server:
You should understand most of the code, if you understood the first example. We're using the echo
command again to output a string of text in the first line. In the second line, we use the echo command
along with a function, time(). The function time() returns the current server time, in the number of
seconds since January 1st, 1970 (known as the time since the Unix era, or the timestamp), so by placing it
after the echo command we're sending the current server time to the web browser whenever the page
loads. The way that the page looks, then, will be different every second of the day!
While we haven't covered much in terms of PHP, there are plenty of tutorials online for anyone looking
to learn more. There are a number of high quality tutorials listed on the book site, under in the Third
Party Tutorials section. We will be covering a bit more in the next chapter, since we'll be using PHP
together with the MySQL we'll learn about to store information in a database. You can expect to spend
30-40 hours learning how to do more complicated tasks like adding a web form to a web page, but once
you understand the basics, there's no limit to what you can do with PHP!
В© Г‰toile Web Design, 2012.
Page 18
MySQL Chapter
Another language that smaller sites can get by without is MySQL, which is used to store information
about your visitors, orders, or products in a database. Once again, there are a number of alternatives to
MySQL, such as MicrosoftSQL Server and Rails, but MySQL is the most popular and widely used of the
database systems online. For readers who know absolutely nothing about database design or structures,
it might be helpful to read an introduction to the basics of using creating a database before reading the
rest of this chapter (some suggested links are available in the More to Explore section of the book site),
as this chapter will move quite quickly while covering the basics.
To understand MySQL and database design in general in this chapter, we’ll use an example database
tracking the date and time of each visit to our factitious web page. In practice, such a simple database
could probably be replaced with a service like Google Analytics, which would provide a much richer set
of information about visitors on top of the dates and times that they visited. Covering a simple example,
though, should make it easier to understand the creation and use of a database.
To begin with, we're going to need to create a table in our database with three fields: Visit_ID, a unique
ID automatically created for each entry, Visit_Date, which will store the date of the visit, and Visit_Time,
which will track the time of day that the visit occurred.
Skip to next non-DIY section
To get started with our database, we first need to connect to the MySQL system and then select the
database that we want to work with using the code below (Sample 4.1 for this entire chapter):
<?php
mysql_connect("localhost", "admin_username", "admin_password") or die(mysql_error());
mysql_select_db("login_database") or die(mysql_error());
?>
The first line tells PHP to connect to the MySQL system at the server called "localhost", using the
username "admin_username" and the password "admin_password". You should change these values to
the ones specific to your database. The second part of the first line, the portion after the "or", means
that If the connection doesn't happen for some reason, then the PHP code will end and print the error
that caused the early ending. The second line tells PHP that the database that you want to connect to is
called "login_database", and again, if for some reason that database can't be selected, the code will end
and print the reason for the early ending.
Now that we've connected to the database, the next step is to create a table within the database that
will store the login information. By convention, MySQL commands are written all in caps, but the
commands aren't case sensitive, so lower case would be fine as well. We create the table using the code
below:
В© Г‰toile Web Design, 2012.
Page 19
<?php
mysql_query(
"CREATE TABLE login_table(
Login_ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(Login_ID),
Login_Date DATE,
Login_Time TIMESTAMP)"
)
or die(mysql_error());
?>
While it might seem confusing at first, this bit of this chapter is the most important part to understand.
In the code above, we're running a "query", which is basically a MySQL command. In the query, we tell
MySQL that we want to create a table called "login_table" (CREATE TABLE login_table). We then tell
MySQL that there will be a field called "Login_ID", which is an integer (INT), which cannot be blank (NOT
NULL), and which should automatically be one number higher than the previous entry whenever a new
entry is inserted (AUTO_INCREMENT). The next line tells MySQL that "Login_ID" will be the primary key
for the field, which means that there can't be multiple entries in the table with the same "Login_ID".
Next we add another field to our table, "Login_Date", which is a date field (DATE), dates being the type
of data that can be stored in that field. The last field which we add to our table is "Login_Time", which is
a timestamp field (TIMESTAMP), meaning it stores a time in the number of seconds since January 1st,
1970. Finally, we tell PHP to stop early if there is an error creating the table, and to report what that
error is.
If you've managed to follow along until here, congratulations! If you're unclear on what we just did, then
it might make sense to re-read the last couple of paragraphs just to make sure that the remainder of this
chapter makes sense.
Now that we've created our table, it's time for us to start adding data to it every time someone visits the
page we've created. We'll do that using the following code:
<?php
$Date = date("Y-m-d");
$Time = time();
mysql_query(
"INSERT INTO login_table(
(Login_Date, Login_Time)
VALUES
('$Date', '$Time)"
)
or die(mysql_error());
В© Г‰toile Web Design, 2012.
Page 20
?>
In the above code, we set the variable "$Date" to hold the current date in the format yyyy-mm-dd using
using the "date" function. Next, we set the variable "$Time" to hold the current time using the "time"
function. These are both PHP lines, and they should be easy enough to understand provided you
understood the previous chapter (if not, there are a number of links to excellent PHP tutorials listed on
the book site).
The portion that's new to this chapter is the MySQL query command, which tells MySQL to insert a new
entry into our login_table (INSERT INTO login_table). We specify that we want to insert data for the
columns Login_Date and Login_Time (Login_Date, Login_Time), then use the VALUES command to
indicate we're about to send values for those columns, and finally pass the values that we'd like to insert
into our new entry ('$Date', '$Time').
The final task we have to accomplish is deciding where to put all of this new code. Since we only need to
create the table one time, we want to put that code into a separate file which can be uploaded to the
server, run one time, and then deleted. For the code which actually records the date and time of visits,
we want to include that in our HTML document, but before anything else has even been sent to the
visitor's browser, so before the opening <html> tag. That way, any visitor who stopped the page halfway
through loading would still be recorded. As always, the code samples are available online if you need
help trying to figure out why you’re getting an error.
В© Г‰toile Web Design, 2012.
Page 21
Javascript/JQuery Chapter
You might be wondering why it seems like we're going to be covering two languages in this final chapter.
What we're really going to be covering is one language, Javascript, as well as a very popular extension
for it known as JQuery. Javascript can be used on its own, but the added simplicity of using JQuery
means that it's quicker to learn to do something useful with both of them together, rather than learning
Javascript on its own.
At this point, we already know how to create a webpage using HTML, how to change its presentation
using CSS, how to process information on the server before it's sent to a visitor's web browser using
PHP, and how to store information for future use in a MySQL database. What does Javascript have to
add to all of this then? Well, Javascript is what takes care of any actions that occur after one page is
loaded, and before a visitor clicks on a link to another page. A great example of Javascript in action is
Google's predictive search, where suggested search terms appear beneath the search input bar as you
type. We're going to look at a much simpler use of Javascript: showing or hiding an image when a visitor
clicks on a button.
As discussed in chapter 4, PHP and server-side languages run on web servers before any information is
sent to a visitor's browser are known as server-side languages. Javascript and any other languages which
run after a document has loaded, such as Flash, are known as client-side languages. They get their name
because they run in a visitor's web client, better known as their web browser.
While this is good for web hosting companies, since their servers don't have to run any Javascript code,
it is not such good news for you, the website developer. Since Javascript is running in your visitors' web
browsers, any visitors who have Javascript switched off (or worse, not installed!) in their browsers won't
see your pages the way you intended. Although it's rare to have a visitor whose browser doesn't run
Javascript, it makes sense to not use it for jobs which are absolutely critical for your site to run correctly
for those rare visitors who won't see its effects.
Now that we've covered what it is, let's cover the basics. Javascript is included in websites in a way that
is very similar to CSS. You can either declare it inline like this (Sample 5.1):
<script type="text/javascript”>
function sayHello() {
alert("Hello Visitor!");
}
window.onload = sayHello;
</script>
Or you can put the above code in a file, save it as "TestScript.js" in the same folder as your HTML
document, and then put this line into the <head> section of your HTML document:
<script type="text/javascript" src="TestScript.js"></script>
В© Г‰toile Web Design, 2012.
Page 22
Now save the document, and reload the page. The result should look something like this, depending on
the web browser you're using:
Let's look at the Javascript code that we wrote to understand what's happening. There are three parts to
the code we wrote. First, we say that we want to create a function called "sayHello". Functions are
simply portions of code which can be called to run later on, as many times as you'd like. You can
"declare" functions in PHP as well to make it easier to keep track of what's going on, but in Javascript,
functions are absolutely necessary to complete even simple tasks. Second, we say that the function
"sayHello" is going to call the built-in "alert" function. The portion inside of the brackets ("Hello Visitor!"
in this case) is what will display in the message box which pops up. Third, now that we've declared the
function, we have to tell the web browser when to run it. In our case, we want the function to run when
the web browser window loads, so we attach it to the "onload event" for the "window". There are a
tonne of events, so check the documentation provided on the pages which are linked to from the More
to Explore section of the book site.
Skip to next non-DIY section
While setting up a message box to appear when a page loads might help you to understand Javascript,
most people would agree that it's not all that helpful (in fact, a lot of people would think that it makes
your site worse!). Instead, we're going to add a button which will let visitors toggle which of the two
paragraphs in our HTML is visible. Before we get started on that, though, we're going to cover what
JQuery is and how to use it on a webpage.
Let's start with what it is: JQuery is a library of functions, which makes it easier to use Javascript on
websites. To use it, we need to include a link to the library in the <head> section of our HTML document,
just like we would to any other javascript file, like this:
<script src="http://code.jquery.com/jquery-latest.js"></script>
Once we've included JQuery in our HTML document, we can take advantage of its functions to easily
select the <div> elements in the section which has the id “rightColumn” in our document, and then hide
the divs (Sample 5.2):
<script type="text/javascript">
В© Г‰toile Web Design, 2012.
Page 23
function hideDivs() {
if ($(“#rightColumn div:first-child”).css(�display’) == “none”) {
$("#rightColumn").children("div").css(�display’, �inline’);
}
else {
$("#rightColumn").children("div").css(�display’, �none’);
}
}
</script>
While the code above might look intimidating, it’s actually very simple to explain. To start, the way we
select the section with “rightColumn” as its id is exactly the same as in CSS. In this section, we’re
creating a function that checks whether the first <div> in the right column has it’s display property set to
none ($(“#rightColumn div:first-child”).css(�display’) == “none”). If it does (the “if” part), then we know
that all of the <div> elements are being hidden right now, so we set the display property of all the <div>
elements in the right column to display �inline’, or as they normally would ($(“#rightColumn div:firstchild”).css(�display’) == �inline’). Otherwise (the “else”part), we know that all of the <div> elements are
being shown right now, and so we set their display property to �none’, or to not show
($("#rightColumn").children("div").css(�display’, �none’);).
“If” statements are incredibly useful in programming, since they let you check the condition of your
webpage before taking an action, and then let you take two different actions depending on the
condition. The “if” statements in programming are very similar to the ones you use in Microsoft Excel. If
you’ve never seen them before, there is some addition literature on programing logic available through
the More to Explore section of the book site.
Next, we need a way to call our hideDivs function. To do that, we’re going to put a button into our HTML
document that will call the function when clicked. We can do that using the following code, inserted
right after the closing </ul> in the left section of our HTML document:
<button onclick=’hideDivs();’>Toggle Right Column Content</button>
While buttons aren’t used all that often in HTML, this code demonstrates how to set up an “onclick”
attribute for an element. The attribute calls whatever function(s) is attached to it, “hideDivs” in this
case. Now just reload your HTML document with the new Javascript code, JQuery include code and the
HTML button, and you should be able to toggle the content of your page like in the picture below (entire
code sample available as Sample 5.3)!
В© Г‰toile Web Design, 2012.
Page 24
The toggle button we created in this chapter is probably not the most useful thing you could add to a
page, but it hopefully gives you an idea of what you can accomplish with Javascript and JQuery. The
possibilities are almost limitless, but be careful not to make any of your sites critical functions depend
on Javascript: if a visitor to your site has it turned off in their browser, they won’t be able to access any
of your amazing content!
В© Г‰toile Web Design, 2012.
Page 25
Conclusion
Creating gorgeous, dynamic sites is all about practice. Now that you’ve read this short introduction to
the technologies in use today, the next step is to go out and practice building websites of your own. As
mentioned throughout the book, there are a bunch of resources linked to from the book site, at
http://www.etoilewebdesign.com/how-to-build-a-website-e-book/. If you’re a small business owner,
we’ve also got a blog with ideas on how to use your site and social media, whether your objective is to
build a better relationship with your current customers or to attract new ones.
Remember that using the appropriate tool for the purpose is the most important part of designing a
great site that’s easy to maintain. Thanks for reading through to the end of this book, and
congratulations on being able to use the most popular technologies used to build the sites you visit
every day on the internet!
В© Г‰toile Web Design, 2012.
Page 26
About Г‰toile Web Design
Г‰toile Web Design is a company based out of Montreal, Quebec, which provides website and web
browser-based solutions for companies. They work with local companies, as well as with a number of
international businesses and non-profits. What sets them apart is the ease of use of their sites and
programs, their focus on the needs of the personnel of the companies they work with, and their helpful
attitude!
В© Г‰toile Web Design, 2012.
Page 27