PHP & MySQL: Novice To Ninja, 6th Edition - Fktpm

Transcription

PHP & MySQL: Novice to Ninja, 6th Editionby Tom Butler and Kevin YankCopyright 2017 SitePoint Pty. Ltd.Product Manager: Simon MackieEnglish Editor: Ralph MasonTechnical Editor: Bruno ŠkvorcCover Designer: Alex Walker

Notice of RightsAll rights reserved. No part of this book may be reproduced, stored in a retrieval system ortransmitted in any form or by any means, without the prior written permission of the publisher,except in the case of brief quotations embodied in critical articles or reviews.

Notice of LiabilityThe author and publisher have made every effort to ensure the accuracy of the informationherein. However, the information contained in this book is sold without warranty, either expressor implied. Neither the authors and SitePoint Pty. Ltd., nor its dealers or distributors will be heldliable for any damages to be caused either directly or indirectly by the instructions contained inthis book, or by the software or hardware products described herein.

Trademark NoticeRather than indicating every occurrence of a trademarked name as such, this book uses thenames only in an editorial fashion and to the benefit of the trademark owner with no intention ofinfringement of the trademark.Published by SitePoint Pty. Ltd.48 Cambridge Street CollingwoodVIC Australia 3066Web: www.sitepoint.comEmail: books@sitepoint.comISBN 978-0-9943469-8-8 (print)ISBN 978-0-9953827-8-7 (ebook)Printed and bound in the United States of America

About Tom ButlerTom is a web developer, a Ph.D student researching software best practices, and universitylecturer from the UK with an interest in programming best practices, separation of concerns anda “less is more” approach to code.

About Kevin YankBefore joining Culture Amp in 2015, Kevin taught a generation of web developers during histime at SitePoint, starting with the first edition of the book that you now hold in your hands.While there, he helped to launch success stories like 99designs and Flippa. More recently, hequizzed web developers on HTML, CSS and JavaScript by leading the team behind Sit the Test,and has spoken at tech conferences around the world. On weekends he performs improvisedtheatre with Impro Melbourne, which is a lot more like building websites than you might expect.

About SitePointSitePoint specializes in publishing fun, practical, and easy-to-understand content for webprofessionals. Visit http://www.sitepoint.com/ to access our blogs, books, newsletters, articles,and community forums. You’ll find a stack of information on JavaScript, PHP, Ruby, mobiledevelopment, design, and more.

PrefaceIt was 1998, I was twelve, and my parents had just bought the family our first modern PC. Itwasn’t long before I had figured out how to change the code for one of my favorite first-personshooter games—little things like making the rocket launcher fire a hundred rockets a secondinstead of one, then having it fire a hundred rockets in every direction and promptly crashingthe game. I was hooked, and I’ve been programming ever since.The game was multiplayer. Other people had also discovered how to change the code, and thearms race quickly escalated. Someone would fire a hundred rockets at me. I’d have a script readythat would instantly build a wall right in front of me to block them all.My opponent would spawn a dozen land mines underneath me. I’d turn off the gravity, thenjump, soaring away from the impending explosion. Everyone could fly. It got to the point whereit was no longer fun. You’d enter a game and someone had written a script to teleport you to theother side of the map, kill you instantly and force you to respawn, repeating the process a dozentimes a second. They’d freeze your controls too, of course.We discovered ways to block all this, but by the end it was a stalemate. Whoever managed toenter the game first could take complete control of it, and no matter how good your scripts were,there was nothing you could do. It was fun while it lasted.That’s how I learned the basics of coding, and that the only limit is your own imagination andcreativity. During that time, I’d also taught myself HTML, and had my own website where Ishared some of my game hacking techniques and scripts. No, the website is not still up. Yes, itwas terrible, full of bad grammar and cheesy animations (which was the style at the time, Ipromise!).By 2000, I had taught myself the basics of PHP/MySQL and was running a website for a groupof fellow gamers. I wrote some crude PHP scripts for posting news on the website, as well aspolls, and even a script for handling our mini-tournament rankings and fixtures.After that, I moved onto writing desktop applications in a horrible language called Delphi,writing tools that aided people in modding various games. I graduated from University in 2007with a degree in Software Engineering, worked for various companies as a PHP developer, andthese days I’m back at the University studying for a PhD and working as a lecturer, spreading mypassion for programming.I’m 31 now, and I’ve been programming for more of my life than not. It’s fun, it’s something Ithoroughly enjoy doing. I’m writing this book to share my knowledge with you and help yousteer clear of some traps that are easy to fall into.Learning to code is very enjoyable and rewarding. You can watch your program come alive asyou build it. However, it can also be an incredibly frustrating experience. In this book, I’m goingto try to use my own experience to give you a smoother ride than I and a lot of developers havehad. I can steer you in the right direction from the start.Before I introduce you to any code, I’m going to give you some general advice aboutprogramming and learning to code which I give to all my students.

Who Should Read This BookThis book is aimed at intermediate and advanced web designers looking to make the leap intoserver-side programming. You’ll be expected to be comfortable with simple HTML, as I’ll makeuse of it without much in the way of explanation. No knowledge of Cascading Style Sheets(CSS) or JavaScript is assumed or required, but if you do know JavaScript, you’ll find it willmake learning PHP a breeze, since these languages are quite similar.By the end of this book, you can expect to have a grasp of what’s involved in building a modernPHP website, the basics of PHP, and tried and tested techniques that are used by developerstoday.

Programming Has ChangedAs a novice developer starting now, there’s a lot more you need to know before you can publisha website than someone who was building a website in 2001.When I started, it was a much simpler time. For example, website security wasn’t much of aconsideration. Unless you were a bank or a company taking credit card payments, there was verylittle chance anyone would target your site.These days, however, every single website is constantly bombarded by bots and scriptsspecifically looking to exploit even the smallest doors you may have left open.The way PHP scripts are written has changed dramatically as well—certainly for the better. It’snow much, much easier to download and use someone else’s code in your own project. Thedownside to this is that you need a much broader understanding of programming concepts beforeyou can do anything useful.To keep up with the competition, and with the needs of more demanding projects, PHP andMySQL have also had to evolve. PHP is now a far more intricate and powerful language than itwas back in 2001, and MySQL is a vastly more complex and capable database. Learning PHPand MySQL today opens up a lot of doors that would have remained closed to the PHP andMySQL experts of 2001.That’s the good news. The bad news is that, in the same way that a butter knife is easier to figureout than a Swiss army knife (and less likely to cause self-injury!), all these dazzling new featuresand improvements have indisputably made PHP and MySQL more difficult for beginners tolearn.

It Takes 10,000 Hours to Become an ExpertThe science behind this statement is questionable, but the sentiment is correct. Programming is askill, and it’s incredibly difficult to master. Don’t expect to become proficient overnight. By theend of this book, you’ll have a good understanding of PHP, but there’s always more to learn,regardless of the level you’re at.Having said that, in programming a little knowledge can go a long way. You’ll be surprised howmuch you can do with just a few tools at your disposal!You’ll find that, after you’ve learned the very basics, you can achieve almost anything you want.There’ll be very little you can’t do, even though you only know a fraction of the programmingconcepts that are out there. The more advanced concepts are about making your code moreefficient, quicker and easier to write, and much simpler to build on top of.

Resist the Temptation to Skip AheadThis is one I reiterate time and time again for my students who miss lectures. Programmingconcepts build on top of each other. For the most part, you need to learn the earlier conceptsbefore you can move on to the next one. If you try to move too fast, you’ll get needlesslyconfused and make it more difficult for yourself.There aren’t many programming concepts that exist in isolation, so if you get stuck, it’s often aresult of not fully understanding an earlier concept. Don’t be afraid to go back and give yourselfa refresher on what you think you already know from before. It’s usually quicker overall thanstruggling and trying to press forward when you get stuck!

The Concorde FallacyIn the late 1970s, the British and French governments continued to fund the Concorde aircrafteven though it was losing vast amounts of money. Their reasoning was that they had alreadyspent so much on the project that, if they scrapped it, they’d lose everything they had invested sofar. Of course, they eventually lost considerably more because they kept throwing money at it. Ifthey had stopped sooner, they would have saved a lot of money in the long run. This is oftenreferred to as the “Concorde fallacy”. There are times when it’s better to cut your losses thankeep working on a failed project!There will come a time when you’ve spent hours on something and it’s just not working. Whenthis happens, take a step back and try to solve the problem in a different way. Use some of thealternative tools you have at your disposal. The solution might not be as elegant, but once youhave it working you can tweak it.Never be afraid to scrap everything and start again. When you’re starting out, you’ll end upwriting a lot of code, trying to fit it into what you’ve done before, and gradually build a monster.And you won’t really understand what the code is doing. It will become unworkable, and you’llget frustrated. Even making the slightest change will be hard work, as it will most likely breaksomething else.When this happens, don’t be afraid to start again from scratch. I’ve lost count of the number oftimes I’ve started a project from scratch after getting it partially completed. You can usually getto the same point you got stuck at within a couple of hours, and you have far neater code and abetter understanding of it as a result!However, I strongly recommend keeping that code as a point of reference, rather than deleting it.Everyone starts off writing terrible code. Ask any programmer to look at some code they wrotewhen they first started and they’ll cringe, even if they only started a few months ago.

You’re Not Learning PHPYes, you read that right. This book is focused entirely on PHP on MySQL, but don’t fall into thetrap of thinking you’re learning PHP. Well, you are learning PHP, but I’m using PHP to teachyou to code.When you learn to drive, you don’t learn to drive a Ford. You learn the concepts of driving, andyou can apply them to any car you get in, even if a few of the controls are in a different place.Concepts you’ll learn here will apply to almost any other language you wish to learn in thefuture. Sure, there are some differences, but the underlying concepts are the same.Once you can program proficiently in one language, you can get to a reasonable standard inanother within a few days! So don’t read this book thinking “I’m learning PHP,” but insteadthink “I’m learning to code.”It’s more important to remember the concepts than the syntax. You can always look up thecorrect syntax, but understanding the underlying concepts is more difficult. Which brings me tomy next point

Getting Braces and Semicolons in the Right Place Isthe Easy PartWhen you start out, you’ll constantly put brackets, braces, semicolons, dots and pretty mucheverything else in the wrong place. You’ll forget to put in a single character and your wholeprogram won’t work.This can be incredibly frustrating at first! But once you get the hang of it, you soon realize thatgetting the syntax right is the easy part. It’s easy because it’s strict. It’s either right or it’s wrong.It works or it doesn’t.The hard part is actually writing the logic, breaking a problem down to its smallest parts so youcan explain it to the computer. The computer will quickly tell you if the syntax is wrong, butthere’s no way for it to tell you whether you’ve given it the right instructions to solve theproblem at hand.

You Won’t Get Anything Done by PlanningYou won’t get anything done by planning. — Karl PilkingtonIf you’ve done any reading about programming, you’ve probably heard that you need to spendlots of time designing your code—that you should carefully plan the logic of your program andhow it will work before writing a single line of code. You’ll come across books and articles thatteach development methodologies, something called “requirements engineering”, diagrams forvisually representing code, and all sorts of tips on how to plan your code out before you write it.For example:There are three fundamental steps you should perform when you have a program to write:1. Define the output and data flows.2. Develop the logic to get to that output.3. Write the program.Notice that writing the program is the last step in writing the program. This is not as silly asit sounds. Remember that physically building the house is the last stage of building thehouse; proper planning is critical before any actual building can start. You will find thatactually writing and typing in the lines of the program is one of the easiest parts of theprogramming process. If your design is well thought out, the program practically writesitself; typing it in becomes almost an afterthought to the whole process.Sam’s Teach Yourself Beginning Programming in 24 HoursI’m now going to say something that will make most programmers wince: ignore that adviceentirely and get stuck into writing code.When I say this in lectures, my students breathe a sigh of relief. They’re there to learn to code,and the best way to learn to code is to start writing.The fundamental problem with this advice is that it forgets a somewhat obvious fact: to designsoftware, you need to know what tools are available and the problems they solve. Otherwise, anydesign you come up with will be meaningless if you don’t know what tools are available.Let’s assume you know nothing about building a house. You don’t know how to use a hammer, asaw, how strong a beam needs to be to support your roof, how deep your foundations need to be,how to plumb in the bathroom, what materials are suitable for which part of the house, etc.You can spend as long on the design as you like and plan things as carefully as possible, butunless you know what your tools are capable of and their limitations, you’ll end up with a designthat doesn’t fully utilize the tools, or a design that just isn’t possible with the tools/materialsavailable to you. Without knowing that you need a six-meter foundation for a three-story house,you can’t design a three-story house.Equally, you can’t design a computer program if you don’t know how to program!To demonstrate my point, here’s a story from a TED talk called “Want to help someone? Shut upand listen”, by Ernesto Strolli.

It was a project where we Italians decided to teach Zambian people how to grow food. Sowe arrived there with Italian seeds in southern Zambia in this absolutely magnificent valleygoing down to the Zambezi River. And we were amazed that the local people in such afertile valley would not have any agriculture. But instead of asking them how come theywere not growing anything, we simply said, ”Thank God we’re here. Just in the nick of timeto save the Zambian people from starvation.”And of course, everything in Africa grew beautifully and we had these magnificenttomatoes. In Zambia, the tomatoes grew even larger than they did in Italy. And we weretelling the Zambians, look how easy agriculture is. When the tomatoes were nice and ripeand red, overnight, some 200 hippos came up from the river and they ate everything. Andwe said to the Zambians, “My God, the hippos.” And the Zambians said, “Yes, that’s whywe have no agriculture here.”Ernesto’s team knew exactly what they were doing. They carefully planned everything out andmanaged to get the result they wanted. However, all that planning and designing was wastedbecause of something they didn’t see coming.Programmers don’t encounter hippos, but there are lots of obstacles you won’t be able toanticipate, and you’ll inevitably run into them. Any time you spend designing is wasted when theequivalent of 200 hippos come and eat your code. You have to scrap the design and start again.During this book, I’ll warn you about the various hippos you might encounter, but it’s a goodidea to test it for yourself. Learn by doing. Rush in. Write some code. It almost certainly won’twork the first time, but you’ll have learned something in the process. Try again with a differentapproach and you’ll come up with something that does work.There’s no way to design a program until you’re aware of the problems you’re likely toencounter and the limitations of the tools available to you.Okay, Design Isn’t All BadTo prevent a wave of hate mail from other programmers, I’m going to conclude this section bysaying that, for professional programmers, spending time up front designing the code beforebuilding it is vital. However, professionals are writing code they may need to work with for yearsor decades to come. The code they write needs to be written in such a way that it’s extensible andeasy for others to follow.During this book, I’ll get you to think about the structure of your code and how to write codethat’s reusable and extensible. But you’re not here to write code that will be used in real projectsand will need to be maintained for years to come. You’re here to learn. Go and find all thosehippos. You’ll learn more from making mistakes than you will from code that works right away.The time you spend planning your code should be proportional to your programming ability. Ifyou’re just starting out, as long as you have a broad understanding of what you want the programto do, jump in and start writing code until it does what you want. You can get stuck and try adifferent approach without feeling like you’re doing it wrong because it’s going against thatdesign you spent hours working on. What I said above about the Concorde fallacy applies here aswell.For the first few chapters, at least, just dive in. Run your code, see if it works. Try solving some

of the problems I set before I give you the solutions. You’ll learn more by discovering thesolutions yourself than blindly typing in the code I give you.As your knowledge grows, you’ll have a firmer understanding of what tools are available and theway problems need to be broken up. Once you reach that level, you can start planning things outin more detail before writing your code.

Conventions UsedYou’ll notice that we’ve used certain typographic and layout styles throughout this book tosignify different types of information. Look out for the following items.

Code SamplesCode in this book is displayed using a fixed-width font, like so: h1 A Perfect Summer's Day /h1 p It was a lovely day for a walk in the park. /p If the code is to be found in the book’s code archive, the name of the example will appear at thetop of the program listing, like this:Footer-example.footer {background-color: #CCC;border-top: 1px solid #333;}Some lines of code should be entered on one line, but we’ve had to wrap them because of pageconstraints. An indicates a line break that exists for formatting purposes only, and should nsive-web design-real-user-testing/?responsive1");Tips, Notes, and WarningsHey, You!Tips provide helpful little pointers.Ahem, Excuse Me .Notes are useful asides that are related—but not critical—to the topic at hand. Think of them asextra tidbits of information.Make Sure You Always . pay attention to these important points.Watch Out!Warnings highlight any gotchas that are likely to trip you up along the way.

Supplementary MaterialsThe book's code archive, which contains the code files used throughout the book.Instructions on how to use the sample code are contained in Appendix A.https://www.sitepoint.com/community/ are SitePoint’s forums, for help on any tricky webproblems.books@sitepoint.com is our email address, should you need to contact us to report aproblem, or for any other reason.

Chapter 1: InstallationIn this book, I’ll guide you as you take your first steps beyond the static world of building webpages with the purely client-side technologies of HTML, CSS, and JavaScript. Together, we’llexplore the world of building websites, and discover the dizzying array of dynamic tools,concepts, and possibilities they open up. Whatever you do, don’t look down!Okay, maybe you should look down. After all, that’s where the rest of this book is. Butremember, you were warned!Before you build your first dynamic website, you must gather together the tools you’ll need forthe job. Like baking a cake, you’ll need the ingredients before you can start following the recipe.In this chapter, I’ll show you how to download and set up the software packages required.If you’re used to building websites with HTML, CSS, and perhaps even a smattering ofJavaScript, you’re probably familiar with uploading the files that make up your site to a certainlocation. It might be a web hosting service you’ve paid for, web space provided by your Internetservice provider (ISP), or maybe a web server set up by the IT department of the company youwork for. In any case, once you copy your files to any of these destinations, a software programcalled a web server is able to find and serve up copies of those files whenever they’re requestedby a web browser like Microsoft Edge, Internet Explorer, Google Chrome, Safari, or Firefox.Common web server software programs you may have heard of include Apache HTTP Server(Apache), NGINX and Internet Information Services (IIS).PHP is a server-side scripting language. You can think of it as a plugin for your web server thatenables it to do more than just send exact copies of the files requested by web browsers. WithPHP installed, your web server will be able to run little programs (called PHP scripts) that can dotasks like retrieve up-to-the-minute information from a database and use it to generate a webpage on the fly, before sending it to the browser that requested it. Much of this book will focuson writing PHP scripts to do exactly that. PHP is completely free to download and use.For your PHP scripts to retrieve information from a database, you must first have a database.That’s where MySQL comes in. MySQL is a relational database management system, orRDBMS. We’ll discuss the exact role it plays and how it works later, but briefly, it’s a softwareprogram that’s able to organize and manage many pieces of information efficiently whilekeeping track of how all those pieces of information are related to each other. MySQL alsomakes that information really easy to access with server-side scripting languages such as PHP.And, like PHP, it’s completely free for most uses.The goal of this first chapter is to set you up with a web server equipped with PHP and MySQL.I’ll provide step-by-step instructions that work on recent versions of Windows, macOS andLinux, so no matter what flavor of computer you’re using, the instructions you need should beright here.(1)

Your Own Web ServerChances are, your current web host’s web server already has PHP and MySQL installed—whichis one of the reasons PHP and MySQL are so popular. If your web host is so equipped, the goodnews is that you’ll be able to publish your first website without having to shop for a web hostthat supports the right technologies.When developing static websites, you can simply load your HTML files directly from your harddisk into your browser to see how they look. There’s no web server software involved when youdo this, which is fine, because web browsers can read and understand HTML code all bythemselves.However, when it comes to dynamic websites built using PHP and MySQL, your web browserneeds some help. Web browsers are unable to understand PHP scripts. Instead, PHP scriptscontain instructions for a PHP-savvy web server to execute in order to generate the HTML codethat browsers can understand.Even if you have an existing web host that supports PHP, you’re still going to want to be able torun PHP scripts yourself without needing to use someone else’s server. For this, you’ll need toset up your own web server. The word “server” might make you think of a large, air-conditionedroom filled with big computers in racks. But don’t worry, you don’t need any fancy newhardware. Your laptop or desktop will work just fine.To run PHP scripts on your web host, you need to write them in your editor, open your FTP orSSH client and upload them to the server. Only then can you see the result in your browser bynavigating to the URI of the file you created. If you made a mistake and there’s an error, you’llneed to change the code, go back into your FTP program, upload the file again and then reloadthe page. This is tedious, and uses up precious time that you could be using to write code. Byrunning a server on your own PC, you’ll be able to save a file in your editor and view thechanges in your browser by simply refreshing the page—no file uploading required. This is a realtime saver, and one of the biggest (although not only!) advantages of running a server on yourPC—even if you have a perfectly good web host already.So how do you get a web server running on your PC? There are three methods of achieving this,each with its own advantages and disadvantages.Server Setup 1: Manually Installing All the Software ComponentsApache is a web server, and like most software it comes with an installer that lets you easily setit up on your PC. Without much effort, you can have it serve web pages. However, there arehundreds of configuration options, and unless you know what you’re doing, it can be timeconsuming and confusing to get it working for developing PHP websites.For our purposes of running PHP scripts, a web server alone is not enough. For manualinstallation, you’ll also need to install PHP—which doesn’t have an installer—and configure it.As with Apache, there are lots of options, and the defaults are set up as if you’re running a livewebsite. For developing code, this is bad, as there are no errors shown. If you made a mistake,you’ll get a blank page with no indication of what went wrong. Even a single character out ofplace—such as a missing brace or semicolon—will give you a blank page, with no indication of(2)

what caused the problem. To solve this, you’ll need to manually configure the PHP installationand tweak the settings to show error messages and enable other tools that make development amore pleasant task.You’ll also need to configure Apache to talk with PHP, so that when someone connects to theserver and requests a file with a .php extension, the file is first sent to PHP for processing.For this book, you’ll also want MySQL, which means manually installing and configuring that aswell.Apache, MySQL and PHP each have dozens of configuration options, and unless you knowexactly what you’re doing, they can be difficult to set up. Even if you’re an expert, it will take atleast an hour to get everything working!Manual installation requires a significant amount of knowledge or research and is beyond thescope of this book. Although being able to configure a server is a useful skill, it doesn’t help youlearn how to program using PHP—which is what you’re really interested in if you’re reading thisbook.This option is not for the faint hearted, and even for seasoned professionals it’s very easy to misssome important settings. Luckily for us, we don’t need to worry about setting up and configuringall the software individually.Server Setup 2: Pre-packaged InstallationsThe problems with manual installations have been recognized by groups of developers over theyears, and to overcome them they’ve built pre-packaged installations—a single installer thatinstalls PHP, Apache, MySQL and other relevant software, all pre-configured with appropriatesettings for developers like you. Some example packages are XAMPP (X, Apache, MySQL,PHP, Perl), WAMP (Windows, Apache, MySQL, PHP) and LAMP (Linux, Apache, MySQL,PHP).This is obviously a lot simpler than manually installing each piece of software, and doesn’trequire learning how to configure your server. It’s quick and easy and a lot better than a manualinstallation, though there are still a couple of problems you may encounter with this method:1. Your web host is probably running Linux, but your PC probably isn’t. Although Apache,MySQL and PHP work in Windows, Linux or macOS, there are some big differencesbetween the way the operating systems work. On Windows, file names are not casesensitive, meaning that FILE.PHP is the same as file.php and fIlE.pHp.

MySQL have also had to evolve. PHP is now a far more intricate and powerful language than it was back in 2001, and MySQL is a vastly more complex and capable database. Learning PHP and MySQL today opens up a lot of doors that would have remained closed to the PHP and