Web Coding & Development All-in-One For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2018 by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions
.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies
.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com
. For more information about Wiley products, visit www.wiley.com
.
Library of Congress Control Number: 2018935649
ISBN: 978-1-119-47392-3; ISBN: 978-1-119-47383-1 (ePDF); ISBN: 978-1-119-47379-4 (ePub)
When the web first came to the attention of the world’s non-geeks back in the mid-1990s, the vastness and variety of its treasures were a wonder to behold. However, it didn’t take long before a few courageous and intrepid souls dug a little deeper into this phenomenon and discovered something truly phenomenal: They could make web pages, too!
Why was that so amazing? Well, think back to those old days and think, in particular, of what it meant to create what we now call content. Think about television shows, radio programs, magazines, newspapers, books, and the other media of the time. The one thing they all had in common was that their creation was a decidedly uncommon thing. It required a team of professionals, a massive distribution system, and a lot of money. In short, it wasn’t something that your average Okie from Muskogee would have any hope of duplicating.
The web appeared to change all of that because learning HTML was within the grasp of anybody who could feed himself, it had a built-in massive distribution system (the Internet, natch), and it required little or no money. For the first time in history, content was democratized and was no longer defined as the sole province of governments and mega-corporations.
Then reality set in.
People soon realized that merely building a website wasn’t enough to attract “eyeballs,” as the marketers say. A site had to have interesting, useful, or fun content, or people would stay away in droves. Not only that, but this good content had to be combined with a solid site design, which meant that web designers needed a thorough knowledge of HTML and CSS.
But, alas, eventually even all of that was not enough. To make their websites dynamic and interesting, to make their sites easy to navigate, and to give their sites those extra bells and whistles that surfers had come to expect, something more than content, HTML, and CSS was needed.
That missing link was code.
What we’ve all learned the hard way over the past few years is that you simply can’t put together a world-class website unless you have some coding prowess in your site design toolkit. You need to know how to program your way out of the basic problems that afflict most sites; how to use scripting to go beyond the inherent limitations of HTML and CSS; and how to use code to send and receive data from a web server. And it isn’t enough just to copy the generic scripts that are available on the web and paste them into your pages. First of all, most of those scripts are very poorly written, and second of all, they invariably need some customization to work properly on your site.
My goal in this book is to give you a complete education on web coding and development. You learn how to set up the tools you need, how to use HTML and CSS to design and build your site, how to use JavaScript and jQuery to program your pages, and how to use PHP and MySQL to program your web server. My aim is to show you that these technologies aren’t hard to learn, and that even the greenest rookie programmers can learn how to put together web pages that will amaze their family and friends (and themselves).
If you’re looking for lots of programming history, computer science theory, and long-winded explanations of concepts, I’m sorry but you won’t find it here. My philosophy throughout this book comes from Linus Torvalds, the creator of the Linux operating system: “Talk is cheap. Show me the code.” I explain what needs to be explained and then I move on without further ado (or, most of the time, without any ado at all) to examples and scripts that do more to illuminate a concept that any verbose explanations I could muster (and believe me, I can muster verbosity with the best of them).
How you approach this book depends on your current level of web coding expertise (or lack thereof):
This book is not a primer on the Internet or on using the World Wide Web. This is a coding and development book, pure and simple. This means I assume the following:
Yep, that’s it.
If you’ve never done a stitch of computer programming before, even if you’re not quite sure what programming really is, don’t worry about it for a second because I had you in mind when I wrote this book. For too many years programming has been the property of “hackers” and other technowizards. That made some sense because the programming languages they were using — with bizarre names such as C++ and Perl — were exceedingly difficult to learn, and even harder to master.
This book’s main coding technologies — HTML, CSS, JavaScript, jQuery, PHP, and MySQL — are different. They’re nowhere near as hard to learn as those for-nerds-only languages. I honestly believe that anyone can become a savvy and successful web coder, and this book is, I hope, the proof of that assertion. Just follow along, examine my code carefully (particularly in the first few chapters), and practice what you learn, and you will master web coding and development.
What if you’ve done some programming in the past? For example, you might have dipped a toe or two in the JavaScript waters already, or you might have dabbled with HTML and CSS. Will this book be too basic for you? No, not at all. My other main goal in this book is to provide you with a ton of truly useful examples that you can customize and incorporate into your own site. The book’s first few chapters start slowly to avoid scaring off those new to this programming business. But once you get past the basics, I introduce you to lots of great techniques and tricks that will take your web coding skills to a higher level.
Some extra content for this book is available on the web. Go online to find the following:
mcfedries.com/webcodingfordummies
The examples are organized by book and then by chapter within each book. For each example, you can view the code, copy it to your computer’s clipboard, and run the code in the browser.
webdev.mcfedries.com
You won’t break anything, so feel free to use the site run some experiments and play around with HTML, CSS, JavaScript, and jQuery.
Book 1
Chapter 1
IN THIS CHAPTER
Learning how the web works
Understanding the front-end technologies of HTML and CSS
Understanding the back-end technologies of MySQL and PHP
Figuring out how JavaScript fits into all of this
Learning about dynamic web pages, web apps, and mobile web apps
More than mere consumers of technology, we are makers, adapting technology to our needs and integrating it into our lives.
— DALE DOUGHERTY
The 1950s were a hobbyist’s paradise with magazines such as Mechanix Illustrated and Popular Science showing the do-it-yourselfer how to build a go-kart for the kids and how to soup up a lawnmower with an actual motor! Sixty years later, we’re now firmly entrenched in the age of do-it-yourself tech, where folks indulge their inner geek to engage in various forms of digital tinkering and hacking. The personification of this high-tech hobbyist renaissance is the maker, a modern artisan who lives to create things, rather than merely consume them. Today’s makers exhibit a wide range of talents, but the skill most sought-after not only by would-be makers themselves, but by the people who hire them, is web coding and development.
Have you ever visited a website and thought, “Hey, I can do better than that!”? Have you found yourself growing tired of merely reading text and viewing images that someone else has put on the web? Is there something creative in you — stories, images, expertise, opinions — that you want to share with the world? If you answered a resounding “Yes!” to any of these questions, then congratulations: You have everything you need to get started with web coding and development. You have, in short, the makings of a maker.
If, as the King said very gravely in Lewis Carroll’s Alice in Wonderland, it’s best to “begin at the beginning,” then you’ve come to the right place. My goal here is to get you off on the right foot by showing you what web coding and web development are.
Before you can understand web coding and development, you need to take a step back and understand a bit about how the web itself works. In particular, you need to know what happens behind the scenes when you click a link or type a web page address into your browser. Fortunately, you don’t need to be a network engineer to understand this stuff, because I can explain the basics without much in the way of jargon. Here’s a high-level blow-by-blow of what happens:
You tell the web browser the web page you want to visit.
You do that either by clicking a link to the page or by typing the location — known as the uniform resource locator or URL (usually pronounced “you-are-ell,” but also sometimes “earl”) — into the browser’s address bar (see Figure 1-1).
The browser decodes the URL.
Decoding the URL means two things: First, it checks the prefix of the URL to see what type of resource you’re requesting; this is usually http://
or https://
, both of which indicate that the resource is a web page. Second, it gets the URL's domain name — the something.com
or whatever.org
part — and asks the domain name system (DNS) to translate this into a unique location — called the IP (Internet Protocol) address — for the web server that hosts the page (see Figure 1-2).
The browser contacts the web server and requests the web page.
With the web server's unique IP address in hand, the web browser sets up a communications channel with the server and then uses that channel to send along a request for the web page (see Figure 1-3).
The web server decodes the page request.
Decoding the page request involves a number of steps. First, if the web server is shared between multiple user accounts, the server begins by locating the user account that owns the requested page. The server then uses the page address to find the directory that holds the page and the file in which the page code is stored (see Figure 1-4).
The web browser decodes the web page file.
Decoding the page file means looking for text to display, instructions on how to display that text, and other resources required by the page, such as images and fonts (see Figure 1-6).
FIGURE 1-1: One way to get to a web page is to type the URL in the browser’s address bar.
FIGURE 1-2: The browser extracts the prefix, domain, and the server address from the URL.
FIGURE 1-3: The browser asks the web server for the web page.
FIGURE 1-4: The server uses the page request to get the account, directory, and filename.
FIGURE 1-5: The web server sends the requested web page file to the browser.
FIGURE 1-6: The web browser scours the page file to see if it needs anything else from the server.
FIGURE 1-7: The web browser goes back to the server to ask for the other data needed to display the web page.
FIGURE 1-8: The web server sends the browser the rest of the requested files.
FIGURE 1-9: At long last, the web browser displays the web page.
Another way to look at this process is to think of the web as a giant mall or shopping center, where each website is a storefront in that mall. When you request a web page from a particular site, the browser takes you into that site’s store and asks the clerk for the web page. The clerk goes into the back of the store, locates the page, and hands it to the browser. The browser checks the page and asks for any other needed files, which the clerk retrieves from the back. This process is repeated until the browser has everything it needs, and it then puts all the page pieces together for you, right there in the front of the store.
This metaphor might seem a bit silly, but it serves to introduce yet another metaphor, which itself illustrates one of the most important concepts in web development. In the same way that our website store has a front and a back, so, too, is web development separated into a front end and a back end:
As a consumer of web pages, you only ever deal with the front end, and even then you only passively engage with the page by reading its content, looking at its images, or clicking its links or buttons.
However, as a maker of web pages — that is, as a web developer — your job entails dealing with both the front end and the back end. Moreover, that job includes coding what others see on the front end, coding how the server gathers its data on the back end, and coding the intermediate tasks that tie the two together.
As I mention in the previous section, the front end of the web development process involves what users see and interact with in the web browser window. It’s the job of the web developer to take a page design — which you might come up with yourself, but is more often something cooked up by a creative type who specializes in web design — and make it web-ready. Getting a design ready for the web means translating the design into the code required for the browser to display the page somewhat faithfully. (I added the hedge word “somewhat” there because it’s not always easy to take a design that looks great in Photoshop or Illustrator and make it look just as good on the web. However, with the techniques you learn in this book, you’ll almost always be able to come pretty close.)
You need code to create the front end of a web page because without it your page will be quite dull. For example, consider the following text:
COPENHAGEN—Researchers from Aalborg University announced today that they have finally discovered the long sought-after Soup-Nuts Continuum. Scientists around the world have been searching for this elusive item ever since Albert Einstein's mother-in-law proposed its existence in 1922.
"Today is an incredible day for the physics community and for humanity as a whole," said senior researcher Lars Grüntwerk. "Today, for the first time in history, we are on the verge of knowing everything from soup to, well, you know, nuts."
If you plop that text onto the web, you get the result shown in Figure 1-10. As you can see, the text is very plain, and the browser didn’t even bother to include the paragraph break.
FIGURE 1-10: Text-only web pages are dishwater-dull.
So, if you can’t just throw naked text onto the web, what’s a would-be web developer to do? Ah, that’s where you start earning your web scout merit badges by adding code that tells the browser how you want the text displayed. That code comes in two flavors: structure and formatting.
The first thing you usually do to code a web page is give it some structure. This means breaking up the text into paragraphs, adding special sections such as a header and footer, organizing text into bulleted or numbered lists, dividing the page into columns, and much more. The web coding technology that governs these and other web page structures is called (deep breath) Hypertext Markup Language, or HTML, for short.
HTML consists of a few dozen special symbols called tags that you sprinkle strategically throughout the page. For example, if you want to tell the web browser that a particular chunk of text is a separate paragraph, you place the <p>
tag (the p
here is short for paragraph) before the text and the </p>
tag after the text.
In the code that follows, I've added these paragraph tags to the plain text that I show earlier. As you can see in Figure 1-11, the web browser displays the text as two separate paragraphs, no questions asked.
<p>
COPENHAGEN—Researchers from Aalborg University announced today that they have finally discovered the long sought-after Soup-Nuts Continuum. Scientists around the world have been searching for this elusive item ever since Albert Einstein's mother-in-law proposed its existence in 1922.
</p>
<p>
"Today is an incredible day for the physics community and for humanity as a whole," said senior researcher Lars Grüntwerk. "Today, for the first time in history, we are on the verge of knowing everything from soup to, well, you know, nuts."
</p>
FIGURE 1-11: Adding paragraph tags to the text separates the text into two paragraphs.
HTML takes care of the structure of the page, but if you want to change the formatting of the page, then you need to turn to a second front-end technology: cascading style sheets, known almost universally as just CSS. With CSS in hand, you can play around with the page colors and fonts, you can add margins and borders around things, and you can mess with the position and dimensions of page elements.
CSS consists of a large number of properties that enable you to customize many aspects of the page to make it look the way you want. For example, the width
property lets you specify how wide a page element should be; the font-family
property enables you to specify a typeface for an element; and the font-size
property lets you dictate the type size of an element. Here's some CSS code that applies all three of these properties to every p
element (that is, every <p>
tag) that appears in a page (note that px
is short for pixels):
p {
width: 700px;
font-family: sans-serif;
font-size: 24px;
}
When used with the sample text from the previous two sections, you get the much nicer-looking text shown in Figure 1-12.
FIGURE 1-12: With the judicious use of a few CSS properties, you can greatly improve the look of a page.
Many web pages are all about the front end. That is, they consist of nothing but text that has been structured by HTML tags and styled by CSS properties, plus a few extra files such as images and fonts. Sure, all these files are transferred from the web server to the browser, but that’s the extent of the back end’s involvement.
These simple pages are ideal when you have content that doesn’t change very often, if ever. With these so-called static pages, you plop in your text, add some HTML and CSS, perhaps point to an image or two, and you’re done.
But there’s another class of page that has content that changes frequently. It could be posts added once or twice a day, or sports or weather updates added once or twice an hour. With these so-called dynamic pages, you might have some text, HTML, CSS, and other content that’s static, but you almost certainly don’t want to be updating the changing content by hand.
Rather than making constant manual changes to such pages, you can convince the back end to do it for you. You do that by taking advantage of two popular back-end technologies: MySQL and PHP.
MySQL is a relational database management system that runs on the server. You use it to store the data you want to use as the source for some (or perhaps even all) of the data you want to display on your web page. Using a tool called Structured Query Language (SQL, pronounced “ess-kew-ell,” or sometimes “sequel”), you can specify which subset of your data you want to use.
PHP is a programming language used on the server. It’s a very powerful and full-featured language, but for the purposes of this book, you use PHP mostly to interact with MySQL databases. You can use PHP to extract from MySQL the subset of data you want to display, manipulate that data into a form that’s readable by the front end, and then send the data to the browser.
Okay, so now you have a front end consisting of HTML structure and CSS styling, and a back end consisting of MySQL data and PHP code. How do these two seemingly disparate worlds meet to create a full web page experience?
In the website-as-store metaphor that I introduce earlier in this chapter, I use the image of a store clerk taking an order from the web browser and then going into the back of the store to fulfill that order. That clerk is the obvious link between the front end and the back end, so what technology does that clerk represent? She actually represents two technologies that I use in this book: JavaScript and jQuery.
The secret sauce that brings the front end and the back end together to create the vast majority of the web pages you see today, is JavaScript. JavaScript is a programming language and is the default language used for coding websites today. JavaScript is, first and foremost, a front-end web development language. That is, JavaScript runs inside the web browser and it has access to everything on the page: the text, the images, the HTML tags, the CSS properties, and more. Having access to all the page stuff means that you can use code to manipulate, modify, even add and delete web page elements.
But although JavaScript runs in the browser, it’s also capable of reaching out to the server to access back-end stuff. For example, with JavaScript you can send data to the server to store that data in a MySQL database. Similarly, with JavaScript you can request data from the server and then use code to display that data on the web page.
JavaScript is extremely powerful, but sometimes using certain JavaScript statements and structures can be a bit unwieldly. For example, here’s a bit of JavaScript code:
var subheads = document.getElementsByClassName('subheadings');
This will no doubt look like gibberish to you now, but my purpose here is only to have you remark the length of that statement. Now compare the following:
var subheads = $('.subheadings');
Believe it or not, these statements do exactly the same thing, except the second one is written using a JavaScript package called jQuery. jQuery is a collection — called a library — of JavaScript code that makes it easier and faster to code for the web. Not only does jQuery give you shorter ways to reference web page elements, but it also incorporates routines that make it easier for you to manipulate HTML tags and CSS properties, navigate and manipulate web page elements, add animation effects, and much more.
It’s one thing to know about HTML and CSS and PHP and all the rest, but it’s quite another to actually do something useful with these technologies. That, really, is the goal of this book, and to that end the book spends several chapters later covering how to create wonderful things called dynamic web pages. A dynamic web page is one that includes content that, rather than being hard-wired into the page, is generated on-the-fly from the web server. This means the page content can change based on a request by the user, by data being added to or modified on the server, or in response to some event, such as the clicking of a button or link.
It likely sounds a bit like voodoo to you now, so perhaps a bit more detail is in order. For example, suppose you want to use a web page to display some data that resides on the server. Here’s a general look at the steps involved in that process:
JavaScript determines the data that it needs from the server.
JavaScript has various ways it can do this, such as extracting the information from the URL, reading an item the user has selected from a list, or responding to a click from the user.
JavaScript sends a request for that data to the server.
In most cases, and certainly in every case you see in this book, JavaScript sends this request by calling a PHP script on the server.
The PHP script receives the request and passes it along to MySQL.
The PHP script uses the information obtained from JavaScript to create an SQL command that MySQL can understand.
The PHP script manipulates the returned MySQL data into a form that JavaScript can use.
JavaScript can’t read raw MySQL data, so one of PHP’s most important tasks is to convert that data into a format called JavaScript Object Notation (JSON, for short, and pronounced like the name Jason) that JavaScript is on friendly terms with (see Book 6, Chapter 1 for more about this process).
JavaScript displays the data on the web page.
One of the joys of JavaScript is that you get tremendous control over how you display the data to the user. Through existing HTML and CSS, and by manipulating these and other web page elements using JavaScript, you can show your data in the best possible light.
You no doubt have a bunch of apps residing on your smartphone. If you use Windows 10 on your PC, then you have not only the pre-installed apps such as Mail and Calendar, but you might also have one or more apps downloaded from the Windows Store. If the Mac is more your style, then you’re probably quite familiar with apps such as Music and Messages, and you might have installed a few others from the App Store. We live, in other words, in a world full of apps which, in the context of your phone or computer, are software programs dedicated to a single topic or task.
So what then is a web app? It’s actually something very similar to an app on a device or PC. That is, it’s a website, built using web technologies such as HTML, CSS, and JavaScript, that has two main characteristics:
In short, a web app is a website that looks and acts like an app on a device or computer. This is opposed to a regular website, which usually tackles several topics or tasks and has an interface that for the most part only enables users to navigate the site.
In late 2016, the world reached a milestone of sorts when the percentage of people accessing the web via mobile devices such as smartphones and tablets surpassed the percentage of people doing the web thing using desktops and notebooks. The gap between mobile web users and everyone else has only widened since then, so it’s safe to say that we live in a mobile web world now.
What does that mean for you as a web developer? It means you can’t afford to ignore mobile users when you build your web pages. It means you can’t code your web pages using a gigantic desktop monitor and assume that everything will look great on a relatively tiny smartphone screen. It means that you’d do well to embrace the mobile web in a big old bear hug by creating not just web apps, but mobile web apps. What’s the difference? A mobile web app is the same as a web app — that is, it has content and an interface dedicated to a single topic or task — but with a design built from the ground up to look good and work well in a mobile device. This is known as the mobile-first approach to web development, and it’s one of the hottest topics in the web coding world.
After all this talk of HTML, CSS, MySQL, JavaScript, and jQuery, after the bird’s-eye view of dynamic sites, web apps, and mobile web apps, you might be wondering when the heck I’m going to answer the most pressing question of the all: What in the name of Sir Tim Berners-Lee (inventor of the web) is the difference between web coding and web development?
I’m glad you asked! Some people would probably answer that question by saying that there’s no real difference at all, because “web coding” and “web development” are two ways of referring to the same thing: Creating web pages using programming tools.
Hey, it’s a free country, but to my mind I think there’s a useful distinction to be made between web coding and web development:
However you look at it, this book teaches you everything you need to know to become both a web coder and a web developer.
Chapter 2
IN THIS CHAPTER
Understanding the need for a web development environment
Gathering the tools you need for a local development setup
Installing a local web development environment on a Windows PC
Installing a local web development environment on a Mac
Learning what to look for in a good text editor
He is happiest, be he king or peasant, who finds peace in his home.
— JOHANN WOLFGANG VON GOETHE
One of the truly amazing things about web development is that, with the exception of the databases on the server, all you ever work with are basic text files. But surely all the structure you add with HTML tags requires some obscure and complex file type? No way, José: It’s text all the way down. What about all that formatting stuff associated with CSS? Nope: nothing but text. PHP? Text. JavaScript and jQuery? Text and, again, text.
What this text-only landscape means is that you don’t need any highfalutin, high-priced software to develop for the web. A humble text editor is all you require to dip a toe or two in the web coding waters.
But what if you want to get more than your feet wet in web coding? What if you want to dive in, swim around, perhaps do a little snorkeling? Ah, then you need to take things up a notch or three and set up a proper web development environment on your computer. This will give you everything you need to build, test, and refine your web development projects. In this chapter, you get your web coding adventure off to a rousing start by exploring how to set up a complete web development environment on your Windows PC or Mac.