THE EASIEST WAY TO LEARN PHP PHP & MYSQL

Transcription

EDITIONSIXTHALL CODE AVAILABLE TO DOWNLOADTHE EASIEST WAY TO LEARN PHP Install PHP & MySQL on Windows, Mac OS X, or Linux Gain a thorough understanding of PHP syntaxYOUR AUTHORSTOMBUTLER Write robust, maintainable, best practice code Build a working content management system (CMS)SITEPOINT BOOKSBefore joining Culture Amp in 2015,Kevin taught a generation of webdevelopers during his time atSitePoint, starting with the first editionof the book that you now hold in yourhands. While there, he helped tolaunch success stories like 99designsand Flippa. More recently, he quizzedweb developers on HTML, CSS andJavaScript by leading the teambehind Sit the Test, and has spoken attech conferences around the world.WEB DEVELOPMENTPRINT ISBN: 978-0-9943469-8-8& YANKUSD 39.95Visit us on the Web at sitepoint.com or for sales and support email books@sitepoint.comBUTLERAdvocate best practice techniquesLead you through practical examplesProvide working code for your websiteMake learning easy and funNOVICE TO NINJAPHP & MYSQL:NOVICE TO NINJAKEVINYANKPHP & MYSQL:BY TOM BUTLER& KEVIN YANKTom is a web developer, a Ph.Dstudent researching software bestpractices, and university lecturer fromthe UK with an interest inprogramming best practices,separation of concerns and a “less ismore” approach to code. Master database design principles and SQL And much more!PHPPHP & MySQL: Novice to Ninja, 6th Edition is a hands-on guideto learning all the tools, principles, and techniques neededto build a professional web application using PHP & MySQL.Comprehensively updated to cover PHP 7 and modern bestpractice, this highly practical and fun book covers everythingfrom installing PHP and MySQL through to creating a completeonline content management system.CAD 52.95SIXTH EDITIONBUILD YOUR OWN POWERFUL WEB APPLICATIONS

iPHP & 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 WalkerNotice 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 thepublisher, 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, eitherexpress or implied. Neither the authors and SitePoint Pty. Ltd., nor its dealers ordistributors will be held liable for any damages to be caused either directly or indirectly bythe instructions contained in this book, or by the software or hardware products describedherein.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 nointention of infringement 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

ii PHP & MySQL: Novice to Ninja, 6th EditionAbout Tom ButlerTom is a web developer, a Ph.D student researching software best practices, anduniversity lecturer from the UK with an interest in programming best practices,separation of concerns and a “less is more” approach to code.About Kevin YankBefore joining Culture Amp in 2015, Kevin taught a generation of web developersduring his time at SitePoint, starting with the first edition of the book that younow hold in your hands. While there, he helped to launch success stories like99designs and Flippa. More recently, he quizzed web developers on HTML, CSSand JavaScript by leading the team behind Sit the Test, and has spoken at techconferences around the world. On weekends he performs improvised theatre withImpro Melbourne, which is a lot more like building websites than you mightexpect.About SitePointSitePoint specializes in publishing fun, practical, and easy-to-understand contentfor web professionals. Visit http://www.sitepoint.com/ to access our blogs, books,newsletters, articles, and community forums. You’ll find a stack of information onJavaScript, PHP, Ruby, mobile development, design, and more.

Table of Contents iiiTable of ContentsPreface .xvWho Should Read This Book .xviProgramming Has Changed.xviIt Takes 10,000 Hours to Become an Expert .xviiResist the Temptation to Skip Ahead .xviiiThe Concorde Fallacy .xviiiYou’re Not Learning PHP .xixGetting Braces and Semicolons in the Right Place Is the Easy Part . xxYou Won’t Get Anything Done by Planning. xxConventions Used . xxiiiSupplementary Materials.xxivChapter 1Installation .1Your Own Web Server . 3Server Setup 1: Manually Installing All the SoftwareComponents . 4Server Setup 2: Pre-packaged Installations . 5Server Setup 3: Virtual Servers. 6

iv PHP & MySQL: Novice to Ninja, 6th EditionYour Own Virtual Server . 8Installation on Windows. 8Installation on macOS. 8Installation on Linux . 9Getting Started with Vagrant . 9Chapter 2Introducing PHP.15Basic Syntax and Statements.18Variables, Operators, and Comments .22Variables .22Operators .23Comments .23Control Structures .24If Statements .25Loops .33Arrays .45User Interaction and Forms .52Passing Variables in Links .53Passing Variables in Forms .62GET or POST? .66Hiding the Seams .66

Table of Contents vPHP Templates .66Security Concerns .69Many Templates, One Controller .73Bring on the Database .77Chapter 3Introducing MySQL.79An Introduction to Databases .80Using MySQL Workbench to Run SQL Queries.81Creating a Database .87Structured Query Language .90Creating a Table.93Adding Data .98A Word of Warning . 104Viewing Stored Data . 105Modifying Stored Data.110Deleting Stored Data . 111Let PHP Do the Typing .112Chapter 4Publishing MySQL Data on theWeb .114

vi PHP & MySQL: Novice to Ninja, 6th EditionThe Big Picture.114Creating a MySQL User Account .116Connecting to MySQL with PHP. 120A Crash Course in Object-oriented Programming . 126Configuring the Connection . 129Sending SQL Queries with PHP . 134Handling SELECT Result Sets. 139Thinking Ahead . 149Inserting Data into the Database . 161Deleting Data from the Database . 173Mission Accomplished . 182Chapter 5Relational Database Design .183Giving Credit Where Credit Is Due . 184Rule of Thumb: Keep Entities Separate . 187SELECT with Multiple Tables . 193Simple Relationships . 199Many-to-many Relationships . 203One for Many, and Many for One . 207Chapter 6Structured PHP Programming .208

Table of Contents viiInclude Files . 209Including HTML Content . 210Including PHP Code . 212Types of Includes. 215Custom Functions and Function Libraries . 216Variable Scope . 220Breaking Up Your Code Into Reusable Functions . 228Using Functions to Replace Queries . 235Updating Jokes . 238Editing Jokes on the Website. 239Delete Function . 243Select Function . 244The Best Way. 246Chapter 7Improving the Insert and UpdateFunctions .247Improving the Update Function . 247Stripping the Trailing Comma . 252Improving the Insert Function . 254Handling Dates . 258Displaying the Joke Date . 265

viii PHP & MySQL: Novice to Ninja, 6th EditionMaking Your Own Tools . 268Generic Functions . 270Using These Functions . 276Repeated Code Is the Enemy . 280Creating a Page for Adding and Editing . 282Further Polishing . 287Moving Forward . 293Chapter 8Objects and Classes .294Time for Class . 295Public vs Private . 300Objects . 301Class Variables. 302Constructors . 309Type Hinting . 313Private Variables . 315Using the DatabaseTable Class . 318Updating the Controller to Use the Class . 322DRY . 326Creating a Controller Class . 327Single Entry Point . 333

Table of Contents ixKeeping it DRY . 340Template Variables . 346Be Careful With Extract . 349Chapter 9Creating an ExtensibleFramework .353Search Engines. 355Make Things Generic . 358Thinking Ahead: User Registration . 360Dependencies . 365URL Rewriting . 373Tidying Up . 378Make it OOP . 378Reusing Code on Different Websites . 386Generic or Project Specific? . 387Making EntryPoint Generic . 389Autoloading and Namespaces . 396Case Sensitivity . 398Implement an Autoloader . 399Redecorating . 400Namespaces. 403

x PHP & MySQL: Novice to Ninja, 6th EditionAutoloading with PSR-4 . 406A Note on Composer . 409And the REST . 410Enforcing Dependency Structure with Interfaces . 419Your Own Framework . 422Chapter 10Allowing Users to RegisterAccounts .423Validating Email Addresses . 433Preventing the Same Person from Registering Twice . 434Securely Storing Passwords . 439Registration Complete. 442Chapter 11Cookies, Sessions, and AccessControl .446Cookies . 447PHP Sessions . 454Counting Visits with Sessions . 457Access Control . 458Logging In . 458

Table of Contents xiProtected Pages. 467Interfaces and Return Types . 472Making Use of the Authentication Class . 474Login Error Message . 476Creating a Login Form . 478Logging Out . 483Assigning Added Jokes to the Logged-in User . 485User Permissions . 488Mission Accomplished? . 490The Sky’s the Limit . 494Chapter 12MySQL Administration.496Backing Up MySQL Databases . 497Database Backups Using MySQL Workbench. 498Database Backups Using mysqlpump . 500Incremental Backups Using Binary Logs . 502MySQL Access Control Tips . 506Host Name Issues . 507Locked Out? . 509Indexes . 510Multicolumn Indexes . 515

xii PHP & MySQL: Novice to Ninja, 6th EditionForeign Keys . 518Better Safe than Sorry . 520Chapter 13Relationships .521Object Relational Mappers . 526Public Properties . 528Methods in Entity Classes. 529Using Entity Classes from the DatabaseTable Class . 532Joke Objects . 540Using the Joke Class . 544References . 545Simplifying the List Controller Action . 546Tidying Up . 378Caching . 550Joke Categories. 553List Page . 558Assigning Jokes to Categories. 560Assigning Categories to Jokes . 574Displaying Jokes by Category. 577Editing Jokes . 583User Roles . 587

Table of Contents xiiiCreating a Form to Assign Permissions . 594Author List . 595Edit Author Permissions. 596Setting Permissions . 599A Different Approach . 600A Crash Course in Binary . 602Be Bit-Wise . 603Back to PHP . 604Storing Bitwise Permissions in the Database . 607Join Table or Bitwise . 609Cleaning Up . 610Editing Others’ Jokes .611Phew!. 614Chapter 14Content Formatting with RegularExpressions .616Regular Expressions . 617String Replacement with Regular Expressions . 621Emphasized Text. 622Paragraphs. 628Hyperlinks . 631

xiv PHP & MySQL: Novice to Ninja, 6th EditionPutting It All Together . 633Sorting, Limiting and Offsets . 639Sorting . 639Pagination with LIMIT and OFFSET . 645Pagination in Categories . 653Achievement Unlocked: Ninja . 657What Next? . 658Appendix AUsing The Sample CodeRepository.660Some Caveats. 661Appendix BLinux Troubleshooting .662

Preface xvPrefaceIt was 1998, I was twelve, and my parents had just bought the family our firstmodern PC. It wasn’t long before I had figured out how to change the code for oneof my favorite first-person shooter games—little things like making the rocketlauncher fire a hundred rockets a second instead of one, then having it fire ahundred rockets in every direction and promptly crashing the game. I washooked, and I’ve been programming ever since.The game was multiplayer. Other people had also discovered how to change thecode, and the arms race quickly escalated. Someone would fire a hundred rocketsat me. I’d have a script ready that would instantly build a wall right in front of meto block them all.My opponent would spawn a dozen land mines underneath me. I’d turn off thegravity, then jump, soaring away from the impending explosion. Everyone couldfly. It got to the point where it was no longer fun. You’d enter a game andsomeone had written a script to teleport you to the other side of the map, kill youinstantly and force you to respawn, repeating the process a dozen times 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. Whoevermanaged to enter the game first could take complete control of it, and no matterhow good your scripts were, there was nothing you could do. It was fun while itlasted.That’s how I learned the basics of coding, and that the only limit is your ownimagination and creativity. During that time, I’d also taught myself HTML, andhad my own website where I shared some of my game hacking techniques andscripts. No, the website is not still up. Yes, it was terrible, full of bad grammarand cheesy animations (which was the style at the time, I promise!).By 2000, I had taught myself the basics of PHP/MySQL and was running awebsite for a group of fellow gamers. I wrote some crude PHP scripts for postingnews on the website, as well as polls, and even a script for handling our minitournament rankings and fixtures.

xvi PHP & MySQL: Novice to Ninja, 6th EditionAfter that, I moved onto writing desktop applications in a horrible languagecalled Delphi, writing tools that aided people in modding various games. Igraduated from University in 2007 with a degree in Software Engineering, workedfor various companies as a PHP developer, and these days I’m back at theUniversity studying for a PhD and working as a lecturer, spreading my passion forprogramming.I’m 31 now, and I’ve been programming for more of my life than not. It’s fun, it’ssomething I thoroughly enjoy doing. I’m writing this book to share my knowledgewith you and help you steer clear of some traps that are easy to fall into.Learning to code is very enjoyable and rewarding. You can watch your programcome alive as you build it. However, it can also be an incredibly frustratingexperience. In this book, I’m going to try to use my own experience to give you asmoother ride than I and a lot of developers have had. I can steer you in the rightdirection from the start.Before I introduce you to any code, I’m going to give you some general adviceabout programming 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 makethe leap into server-side programming. You’ll be expected to be comfortable withsimple HTML, as I’ll make use of it without much in the way of explanation. Noknowledge of Cascading Style Sheets (CSS) or JavaScript is assumed or required,but if you do know JavaScript, you’ll find it will make 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 inbuilding a modern PHP website, the basics of PHP, and tried and testedtechniques that are used by developers today.Programming Has ChangedAs a novice developer starting now, there’s a lot more you need to know beforeyou can publish a website than someone who was building a website in 2001.

Preface xviiWhen I started, it was a much simpler time. For example, website security wasn’tmuch of a consideration. Unless you were a bank or a company taking credit cardpayments, there was very lit

PHP & MySQL: Novice to Ninja, 6th Edition is a hands-on guide to learning all the tools, principles, and techniques needed to build a professional web application using PHP & MySQL. Comprehensively updated to cover PHP 7 and modern best pract