PHP, MySQL® & JavaScript® 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. MySQL is a registered trademark of MySQL AB. JavaScript is a registered trademark of Oracle America, Inc. 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: 2018933793
ISBN 978-1-119-46838-7 (pbk); ISBN 978-1-119-46833-2 (ebk); ISBN 978-1-119-46837-0 (ebk)
The Internet has become an amazing place to shop, do your banking, look up homework assignments, and even keep track of your bowling league scores. Behind all those great applications are a bunch of different web technologies that must all work together to create the web experience you come to expect.
You may think that creating web applications is best left for the professionals, but you’d be surprised by just how well you can do with just a little knowledge and experience! That’s the point of this book.
Think of this book as a reference book. Like the dictionary or an encyclopedia (remember those?), you don’t have to read it from beginning to end. Instead, you can dip into the book to find the information you need and return to it again when you need more. That said, you won’t be disappointed if you work through the book from beginning to end, and you may find it easier to follow along with some of the examples.
In this book, I walk you through all the different technologies involved with creating dynamic web applications that can track data and present it in an orderly and pleasing manner. I cover several key topics that you’ll need to know to create a full-featured, dynamic web application:
Throughout this book you see sidebars (text in gray boxes) and material marked with the Technical Stuff icon. All of these things are skippable. If you have time and are interested, by all means read them, but if you don’t or aren’t, don’t.
Finally, within this book, you may note that some web addresses break across two lines of text. If you’re reading this book in print and want to visit one of these web pages, simply key in the web address exactly as it’s noted in the text, pretending as though the line break doesn’t exist. If you’re reading this as an e-book, you’ve got it easy — just click the web address to be taken directly to the web page.
You don’t need any level of programming experience to enjoy this book and start creating your own web applications. Each chapter walks through all the basics you need to know and doesn’t assume you’ve ever coded before. As long as you’re reasonably comfortable navigating your way around a standard desktop computer, you have all the experience you need!
That said, if you’ve already tried your hand at web programming and you just want to fill in a few holes, this book will work well for you, too!
This book doesn’t expect you to run out and buy any expensive software packages to start your web development career. All the tools that are used in the book are freely available open-source software. I walk you through how to set up a complete development environment, whether you’re working in Microsoft Windows, Apple macOS, or Linux.
I use some icons throughout the book to help you identify useful information. Here’s what the icons are and what I use them for:
In addition to the material in the print or e-book you’re reading right now, you also get access to a free online Cheat Sheet filled with more tips and tricks on building a web application, including accessing any database from your PHP programs, filtering data your program receives from web forms to block unwanted or potentially dangerous data, quickly finding data in a MySQL database, and triggering JavaScript events at predetermined times in a browser. To access this resource go to www.dummies.com
and enter PHP, MySQL & JavaScript All-in-One For Dummies Cheat Sheet in the search box.
This book doesn’t have to be read from beginning to end, so you can dive in wherever you want! Use the Table of Contents and Index to find subjects that interest you. If you already know PHP and JavaScript and you’re just interested in learning how to create a dynamic web application from scratch, start out with Book 6, Chapter 1. If you’re interested in learning how to use one of the framework packages available for PHP, check out Book 7, Chapter 1. Or, if you’re interested in everything, start with Book 1, Chapter 1, and read until the very end.
With the information in this book, you’ll be ready to start creating your own dynamic web applications. Web programming is one of those skills that takes time and practice to get good at, so the more coding you can do, the better you’ll get at it. To get some practice, you may want to offer your services for free at first, to build up a reputation. Find a needy nonprofit organization that you’re interested in supporting and offer to work on its website. They’ll get a great website, and you’ll get a project to add to your résumé!
Don’t stop learning! There are always new things coming out in the web world, even if you just stick to using the same software packages to develop your web applications. Stay plugged in to the PHP world by visiting the official PHP website at www.php.net
or by visiting (and even participating in) one or more of the many PHP forums. Just do some Googling to find them.
Enjoy your newfound skills in developing dynamic web applications!
Book 1
Chapter 1
IN THIS CHAPTER
Understanding how simple web pages work
Incorporating programming into your web page
Storing content in a database
At first, diving into web programming can be somewhat overwhelming. You need to know all kinds of things in order to build a web application that not only looks enticing but also works correctly. The trick to learning web programming is to pull the individual pieces apart and tackle them one at a time.
This chapter gets you started on your web design journey by examining the different pieces involved in creating a simple web page. Then it kicks things up a notch and walks you through dynamic web pages. And finally, the chapter ends by explaining how to store your content for use on the web.
Before you can run a marathon, you need to learn how to walk. Likewise, before you can create a fancy website, you need to know the basics of how web pages work.
Nowadays, sharing documents on the Internet is easy, but it wasn’t always that way. Back in the early days of the Internet, documents were often created using proprietary word-processing packages and had to be downloaded using the cumbersome File Transfer Protocol (FTP). To retrieve a document, you had to know exactly what server contained the document, you had to know where it was stored on the server, and you had to be able to log into the server. After all that, you still needed to have the correct word-processing software on your computer to view the document. As you can imagine, it wasn’t long before a new way of sharing content was required.
To get to where we are today, several different technologies had to be developed:
This section describes the technology that made viewing documents on the Internet work the way it does today.
In 1989, Tim Berners-Lee developed a method of interconnecting documents to make sharing research information on the Internet easier. His creation, the World Wide Web, defined a method for linking documents together in a web structure, so that a researcher could follow the path between related documents, no matter where they were located in the world. Clicking text in one document took you to another document automatically, without your having to manually find and download the related document.
The method Berners-Lee developed for linking documents is called hypertext. Hypertext embeds links that are hidden from view in the document, and directs the software being used to view the document (known as the web browser) to retrieve the referenced document. With hypertext, you just click the link, and the software (the web browser) does all the work of finding and retrieving the related document for you.
Because the document-viewing software does all the hard work, a new type of software had to be developed that was more than just a document viewer. That’s where web browsers came into existence. Web browsers display a document on a computer screen and respond to the reader clicking hypertext links to retrieve other specified documents.
To implement hypertext in documents, Berners-Lee had to utilize a text-based document-formatting system. Fortunately for him, a lot of work had already been done on that.
Markup languages were developed to replace proprietary word-processing packages with a standard way of formatting documents so that they could be read by any type of document viewer on any type of device. This goal is accomplished by embedding tags in the text. Each tag indicates a formatting feature, such as headings, bold or italic text, or special margins. What made markup languages different from word-processing packages is that these tags were common text codes instead of proprietary codes, making it generic enough that any device could read and process them.
The first popular markup language was the Generalized Markup Language (GML), developed by IBM in the 1960s. The International Organization for Standardization (ISO) took up the challenge of creating markup languages and produced the Standard Generalized Markup Language (SGML), mainly based on GML, in the 1980s. However, because SGML was developed to cover all types of document formatting on all types of devices, it’s extremely complex and it wasn’t readily adapted.
Berners-Lee used the ideas developed in SGML to create a simplified markup language that could support his hypertext idea. He called it Hypertext Markup Language (HTML). HTML uses the same concept of tags that SGML uses, but it defines fewer of them, making it easier to implement in software.
An example of an HTML tag is <h1>
. You use this tag to define text that's used as a page heading. Just surround the text with an opening <h1>
tag, and a corresponding closing </h1>
tag, like this:
<h1>This is my heading</h1>
When the browser gets to the <h1>
tag, it knows to format the text embedded in the opening and closing tags using a different style of formatting, such as a larger font or a bold typeface.
To define a hypertext link to another document, you use the <a>
tag:
<a href="anotherdoc.html">Click here for more info</a>
When the reader clicks the Click here for more info text, the browser automatically tries to retrieve the document specified in the <a>
tag. That document can be on the same server or on another server anywhere on the Internet.
HTML development has seen quite a few changes since Berners-Lee created it and turned it over to the World Wide Web Consortium (W3C) to maintain. Table 1-1 shows the path the language has taken.
TABLE 1-1 HTML Versions
Version |
Description |
HTML 1.0 |
Formally released in 1989 as the first public version of HTML |
HTML 2.0 |
Released in 1995 to add interactive elements |
HTML 3.0 |
Released in 1996 but never widely adopted |
HTML 3.2 |
Released in 1997, adding support for tables |
HTML 4.01 |
Released in 1999, widely adopted, and remains an often-used standard |
XHTML 1.0 |
Released in 2001, standardizing HTML around the XML document format |
XHTML 1.1 |
Released in 2002, making updates and corrections to XHTML 1.1 |
HTML 5.0 |
Released in 2014, adding multimedia features |
The HTML version 4.01 standard was the backbone of websites for many years, and it's still used by many websites today. However, HTML version 5.0 (called HTML5 for short) is the future of web development. It provides additional features for embedding multimedia content in web pages without the need for proprietary software plug-ins (such as Adobe Flash Player). Because multimedia is taking over the world (just ask YouTube), HTML5 has grown in popularity. This book focuses on HTML5; all the code included in this book use that standard.
Besides a document-formatting standard, Berners-Lee also developed a method of easily retrieving the HTML documents in a client–server environment. A web server software package runs in the background on a server, listening for connection requests from web clients (the browser). The browser sends requests to retrieve HTML documents from the server. The request can be sent anonymously (without using a login username), or the browser can send a username and password or certificate to identify the requestor.
These requests and responses are defined in the Hypertext Transfer Protocol (HTTP) standard. HTTP defines a set of requests the client can send to the server and a set of responses the server uses to reply back to the client.
This section walks you through the basics of how web servers and web clients use HTTP to interact with each other to move web pages across the Internet.
The web client sends requests to the web server on a standard network communication channel (known as TCP port 80), which is defined as the standard for HTTP communication. HTTP uses standard text requests sent to the server, either requesting information from the server or sending information to the server. Table 1-2 shows the basic HTTP client requests available.
TABLE 1-2 HTTP Client Requests
Request |
Description |
|
Converts the connection into a secure tunnel for sending data |
|
Deletes the specified resource |
|
Requests the specified resource |
|
Requests the title of the specified resource |
|
Retrieves the HTTP requests that the server supports |
|
Applies a modification to a resource |
|
Sends specified data to the server for processing |
|
Stores specified data at a specified location |
|
Sends the received request back to the client |
As shown in Table 1-2, when you ask to view a web page from your client browser, the browser sends the HTTP GET
request to the server, specifying the filename of the web page. The server then responds with a response code along with the requested data. If the client doesn't specify a filename in the GET
request, most servers have a default file with which to respond.
With HTTP, the web server must respond to each client request received. If the client sends a request that the server can’t process, the server must send some type of error code back to the client indicating that something went wrong.
The first part of the server response is a status code and text that the client uses to determine whether the submitted request was successful. The format of the HTTP response uses a three-digit status code, followed by an optional text message that the browser can display. The three-digit codes are broken down into five categories:
The three-digit status code is crucial to knowing what happened with the response. Many status codes are defined in the HTTP standards, providing some basic information on the status of client requests. Table 1-3 shows just a few of the standard HTTP response codes that you may run into.
TABLE 1-3 Common HTTP Server Response Status Codes
Status Code |
Text Message |
Description |
100 |
Continue |
The client should send additional information. |
101 |
Switching Protocols |
The server is using a different protocol for the request. |
102 |
Processing |
The server is working on the response. |
200 |
OK |
The server accepted the request and has returned the response. |
201 |
Created |
The server created a new resource in response to the request. |
202 |
Accepted |
The data sent by the client has been accepted by the server but has not completed processing the data. |
206 |
Partial Content |
The response returned by the server is only part of the full data; more will come in another response. |
300 |
Multiple Choices |
The request matched multiple possible responses from the server. |
301 |
Moved Permanently |
The requested file was moved and is no longer at the requested location. |
302 |
Found |
The requested resource was found at a different location. |
303 |
See Other |
The requested resource is available at a different location. |
304 |
Not Modified |
The requested resource was not modified since the last time the client accessed it. |
307 |
Temporary Redirect |
The requested resource was temporarily moved to a different location. |
308 |
Permanent Redirect |
The requested resource was permanently moved to a different location. |
400 |
Bad Request |
The server cannot process the request. |
401 |
Unauthorized |
The resource requires authentication that the client did not provide. |
402 |
Payment Required |
The requested resource is not freely available. |
403 |
Forbidden |
The resource requires authentication, and the client does not have the proper permission. |
404 |
Not Found |
The requested resource was not located on the server. |
414 |
URI Too Long |
The Uniform Resource Identifier (URI) describing the location of the resource was longer than the server is able to handle. |
415 |
Unsupported Media Type |
The server does not know how to process the requested resource file. |
429 |
Too Many Requests |
The client has sent too many requests within a specific amount of time. |
500 |
Internal Server Error |
An unexpected condition occurred on the server while trying to retrieve the requested resource. |
501 |
Not Implemented |
The server doesn’t recognize the request. |
502 |
Bad Gateway |
The server was acting as a proxy to another server but received an invalid response from the other server. |
503 |
Service Unavailable |
The server is currently unavailable, often due to maintenance. |
505 |
HTTP Version Not Supported |
The server doesn’t support the HTTP standard used by the client in the request. |
507 |
Insufficient Storage |
The server is unable to store the resource due to lack of storage space. |
511 |
Network Authentication Required |
The client is required to authenticate with a network resource to receive the response. |
As you can see from Table 1-3, a web server can return many possible responses. It’s the client’s job to parse the response and determine the next action to take.
If the response indicates the request was successful, the server will follow the response code with the data related to the request, such as the contents of an HTML file. The client must then read the returned data and decide what to do with it. For HTML files, the browser will display the requested file, applying the HTML formatting tags to the data.
The HTML standard defines how browsers perform basic formatting of text, but it doesn’t really provide a way to tell a browser how to display the text. The <h1>
tag indicates that the text should be a heading, but nothing tells the browser just how to display the heading to make it different from any other text on the page.
This is where styling comes into play. Styling allows you to tell the browser just what fonts, sizes, and colors to use for text, as well as how to position the text in the display. This section explains how styling affects how your web pages appear to your visitors.
There are several ways to define styling for an HTML document. The most basic method is what the browser uses by default. When the browser sees an HTML formatting tag, such as the <h1>
tag, it has a predefined font, size, and color that the developer of the browser felt was useful.
That's fine, but what if you want to make some headings black and others red? This is possible with inline styling. Inline styling allows you to define special styles that apply to only one specific tag in the document. For example, to make one heading red, you’d use the following HTML:
<h1 style="color: red">Warning, this is bad</h1>
The style
term is called an attribute of the <h1>
tag. There are a few different attributes you can apply directly to tags within HTML; each one modifies how the browser should handle the tag. The style
attribute allows you to apply any type of styling to this specific <h1>
tag in the document. In this example, I chose to change the color of the text.
Now, you're probably thinking that I’ve just opened another can of worms. What if you want to apply the red color to all the <h1> tags in your document? That’s a lot of extra code to write! Don’t worry, there’s a solution for that.
Instead of inserting styles inline, you can create a style definition that applies to the entire document. This method is known as internal styling. It defines a set of styles at the top of the HTML document that are applied to the entire document. Internal styling looks like this:
<style>
h1 {color: red;}
</style>
Now the browser will display all the <h1>
tags in the document using a red color. But wait, there’s more!
Style listings can be somewhat lengthy for large web pages, and placing them at the top of a document can become cumbersome. Also, if you want to apply the same styles to all the web pages in a website, having to retype or copy all that text can be tiring. To solve that problem, you use an external style sheet.
An external style sheet allows you to define styles just as the internal method does, but in a separate file, called a style sheet. Any web page can reference the same style sheet, and you can apply multiple style sheets to a single web page. You reference the external style sheet using the <link>
tag, like this:
<link rel="stylesheet" href="mystyles.css">
When the browser sees this tag, it downloads the external style sheet, and applies the styles you defined in it to the document.
This all sounds great, but things just got a lot more complicated! Now there are three different locations from which you can define styles for your HTML document, on top of what the browser itself does. How are you supposed to know which ones take precedence over the others?
The Cascading Style Sheet (CSS) standard defines a set of rules that determine just how browsers should apply styles to an HTML document. As the name implies, styles cascade down from a high level to a low level. Styles defined in a higher-level rule override styles defined in a lower-level rule.
The CSS standard defines nine separate levels, which I cover in greater detail in Book 2, Chapter 2, but for now, here are the four most common style levels, in order from highest priority to lowest:
So, any style attributes you set in an element tag override any styles that you set in an internal style sheet, which overrides any styles you set in an external style sheet, which overrides any styles the client browser uses by default. This allows you to set an overall style for your web pages using an external style sheet, and then override those settings for individual situations using the standard element tags.
The CSS standard defines a core set of styles for basic rendering of an HTML document. The first version of CSS (called CSS1) was released in 1996, and it only defined some very rudimentary styles:
The second version of CSS, called — you guessed it! — CSS2, was released in 1998. It added only a few more styling features:
That’s still not all that impressive of a list of styles. Needless to say, more was needed to help liven up web pages. To compensate for that, many browser developers started creating their own style definitions, apart from the CSS standards. These style definitions are called extensions. The browser extensions covered lots of different fancy styling features, such as applying rounded edges to borders and images, making a smoother layout in the web page.
As you might guess, having different extensions to apply different style features in different browsers just made things more complicated. Instead of coding a single style for an element in an HTML document, you needed to code the same feature several different ways so the web page would look the same in different browsers. This quickly became a nightmare.
When work was started on the CSS3 standard in 1999, one of the topics was to rein in the myriad browser extensions. However, things quickly became complicated because all the different browser developers wanted their own extensions included in the new standard.
To simplify the process, the CSS design committee split the CSS standards into separate modules. Each CSS module covers a specific area of styling, such as colors, media support, and backgrounds. Each module could be voted on and released under a different timeline. The downside to this approach is that now each module has been released as a recommended standard at a different time, making the CSS3 standard somewhat difficult to track and implement.
Quite possibly one of the most anticipated features of CSS3 is the ability to define fonts. Fonts have long been the bane of web programmers. When you define a specific font, that font must be installed on your website visitor’s computer in order for the browser to use it. If the font isn’t available, the browser picks a default font to use, which often becomes an ugly mess.
Web fonts allow you to define a font on your server so that every client browser can download the font and render text using it. This is a huge accomplishment! No longer are you reliant on your website visitors having specific fonts installed in their web browsers.
Yet another popular feature of CSS3 is the use of shadows and semitransparent colors in text and other web page elements, such as form objects. These features by themselves can transform an ugly HTML form into a masterpiece.
The combination of HTML5 and CSS3 has greatly revolutionized the web world, allowing developers to create some pretty amazing websites. However, one thing was still missing: the ability to easily change content on the web page.