Php Mysql The Missing Manual Brett Mclaughlin instant download
Php Mysql The Missing Manual Brett Mclaughlin instant download
download
https://ebookbell.com/product/php-mysql-the-missing-manual-brett-
mclaughlin-2362166
Php Mysql The Missing Manual Second Edition 2nd Edition Brett
Mclaughlin
https://ebookbell.com/product/php-mysql-the-missing-manual-second-
edition-2nd-edition-brett-mclaughlin-46096140
https://ebookbell.com/product/php-and-mysql-the-missing-manual-brett-
mclaughlin-43876038
https://ebookbell.com/product/php-and-mysql-the-missing-manual-brett-
mclaughlin-43876034
https://ebookbell.com/product/phpmysql-programming-for-the-absolute-
beginner-andy-harris-4105628
The Php Programming With Mysql The Web Technology Series The Web
Technologies Series 2nd Edition Don Gosselin
https://ebookbell.com/product/the-php-programming-with-mysql-the-web-
technology-series-the-web-technologies-series-2nd-edition-don-
gosselin-2471394
Php 6mysql Programming For The Absolute Beginner 1st Edition Andrew B
Harris
https://ebookbell.com/product/php-6mysql-programming-for-the-absolute-
beginner-1st-edition-andrew-b-harris-4433786
https://ebookbell.com/product/php-6mysql-programming-for-the-absolute-
beginner-andy-harris-50400322
Php Mysql Novice To Ninja Get Up To Speed With Php The Easy Way 6th
Edition Tom Butler
https://ebookbell.com/product/php-mysql-novice-to-ninja-get-up-to-
speed-with-php-the-easy-way-6th-edition-tom-butler-10380008
https://ebookbell.com/product/handson-guide-to-learning-all-the-tools-
principles-and-techniques-needed-to-build-a-professional-web-
application-using-php-mysql-schmitt-46215016
PHP & MySQL
The book that should have been in the box®
Brett McLaughlin
O’Reilly books may be purchased for educational, business, or sales promotional use.
Online editions are also available for most titles (http://my.safaribooksonline.com).
For more information, contact our corporate/institutional sales department: (800)
998-9938 or [email protected].
Printing History:
November 2011: First Edition.
Revision History:
2011-11-09 First release
See http://oreilly.com/catalog/errata.csp?isbn=9780596515867 for release details.
The Missing Manual is a registered trademark of O’Reilly Media, Inc. The Missing
Manual logo, and “The book that should have been in the box” are trademarks of
O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks. Where those designations
appear in this book, and O’Reilly Media is aware of a trademark claim, the
designations are capitalized.
While every precaution has been taken in the preparation of this book, the publisher
assumes no responsibility for errors or omissions, or for damages resulting from the
use of the information contained in it.
ISBN-13: 978-0-596-51586-7
Contents
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
iii
Chapter 6: Generating Dynamic Web Pages. . . . . . . . . . . . . . . . . . . . . . . . . . 143
Revisiting a User’s Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Planning Your Database Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Saving a User’s Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Show Me the User. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Redirection and Revisitation of Creating Users . . . . . . . . . . . . . . . . . . . . . . . . 176
iv Contents
Part Four: Security and the Real World
Chapter 11: Authentication and Authorization. . . . . . . . . . . . . . . . . . . . . . . . 353
Start with Basic Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Abstracting What’s the Same . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Passwords Don’t Belong in PHP Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Passwords Create Security, But Should Be Secure. . . . . . . . . . . . . . . . . . . . 382
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
Contents v
vi Contents
The Missing Credits
About the Author
Brett McLaughlin is a senior level technologist and strategist, active especially in
web programming and data-driven customer-facing systems. Rarely focused on
only one component of a system, he architects, designs, manages, and implements
large-scale applications from start to finish with mission-critical implementations
and deadlines.
Of course, that’s all fancy-talk for saying that Brett’s a geek, spending most of his
day in front of a computer with his hands flying across a keyboard. Currently, he
spends most of his current time working on NASA projects, which sounds much
cooler than it actually is. But hey, maybe that satellite overhead really is controlled
by PHP and MySQL...
Y
ou’ve built a web page in HTML. You’ve even styled it with Cascading Style
Sheets (CSS) and written a little JavaScript to validate your custom-built web
forms. But that wasn’t enough, so you learned a lot more JavaScript, threw in
some jQuery, and constructed a whole lot of web pages. You’ve even moved your
JavaScript into external files, shared your CSS across your entire site, and validated
your HTML with the latest standards.
But now you want more.
Maybe you’ve become frustrated with your website’s inability to store user information
in anything beyond cookies. Maybe you want a full-blown online store, complete with
PayPal integration and details about what’s in stock. Or maybe you’ve simply caught
the programming bug, and want to go beyond what HTML, CSS, and JavaScript can
easily give you.
If any of these are the case—and you may find that all these are the case!—then
learning PHP and MySQL is a great way to take a giant programming step forward.
Even if you’ve never heard of PHP, you’ll find it’s the best way to go from building
web pages to creating full-fledged web applications that store all sorts of informa-
tion in databases. This book shows you how to do just that.
xi
What Is PHP? What Is PHP?
PHP is a programming language. It’s like JavaScript in that you spend most of your
time dealing with values and making decisions about which path through your code
should be followed at any given time. But it’s like HTML in that you deal with out-
put—tags that your users view through the lens of their web browsers. In fact, PHP
in the context of web programming is a bit of a mutt; it does lots of things pretty
well, rather than just doing one single thing. (And if you’ve ever wondered why it’s
called PHP, see the box below.)
Figure I-1
Sure, you can run PHP programs from a Terminal win-
dow or a command shell on Windows. But most of the
time, you won’t. PHP is perfectly suited to the Web,
and that where you’ll spend most of your time.
PHP comes ready to work with HTML forms and web sessions and browser cookies.
It’s great at integrating with your website’s existing authentication system, or letting
you create one of your own. You’ll spend a lot of time not just handing off control to
an HTML page, but actually writing the HTML you’re already familiar with right into
<?php
require '../../scripts/database_connection.php';
<html>
<!-- All your HTML and inline PHP -->
</html>
The result? Pages that are both full of HTML and have dynamic content, like Figure I-2.
Figure I-2
This page is as much PHP
as HTML. It looks up your
visitor’s name in the
database and displays it
dynamically. The menu
creates a Show Profile
option specific to this
user. But there’s still lots
and lots of HTML. This is
PHP at its best: combining
the HTML and even
JavaScript that you know
with the PHP you’re about
to learn.
Introduction xiii
What Is JavaScript Is Loose, PHP Is…Less So
MySQL?
If you’ve written some JavaScript—and if you’re checking out this book, that’s prob-
ably the case—then you know that JavaScript lets you do just about anything you
want. You can occasionally leave out semicolons; you can use brackets, or not; you
can use the var keyword, or not. That sort of looseness is both great for getting
things working quickly, and at the same time, frustrating. It makes finding bugs tricky
at times, and working across browsers can be a nightmare.
PHP is not quite so loose as JavaScript, so it makes you learn a little more structure
and tighten up your understanding of what’s going on as your program is interpreted.
That’s a good thing, as it’ll end up making you tighten up your JavaScript skills, too.
And, perhaps best of all, PHP’s stodgy consistency makes it easier to learn. It gives
you firm rules to hang on to, rather than lots of “You can do this…or this…or this…”
So get ready. There’s lots to learn, but everything you learn gives you something
to build on. And PHP lets you know right away when there’s a problem. You won’t
need to pop open an Error Console or keep an eye out for Internet Explorer’s tiny
yellow warning triangle like you do with JavaScript.
PHP Is Interpreted
PHP code comes in the form of scripts, which are plain text files you write. The PHP
interpreter is a piece of software on your web server that reads that file and makes
sense of it, giving the Web server HTML output and directions about where to go
next, or how to interpret a user’s form entry. Your text file is interpreted, one line at
a time, every time that file is accessed.
This scheme is different from languages like Java or C++, which are compiled. In
those languages, you write in text files, but then run a command that turns those
text files into something else: class files, binary files, pieces of unreadable code that
your computer uses.
The beauty of an interpreted language like PHP—and JavaScript, for that matter—is
that you write your code and go. You don’t need a bunch of tools or steps. You write
PHP. Test it out in the browser. Write some more. It’s fast, and that usually means
it’s pretty fun.
What Is MySQL?
MySQL is a database. It stores your information, your users’ information, and any-
thing else you want to stuff into it. There’s actually a lot more nuance to MySQL—and
SQL, the language in which you’ll interact with MySQL (but better to save that for
Chapter 3—when you’ve got a little PHP and context under your belt).
For now, think of MySQL as a warehouse where you can store things to be looked
up later. Not only that, MySQL provides you a really fast little imp that runs around
finding all that stuff you stuck in the warehouse whenever it’s needed. By the time
you’re through this this book, you’ll love that imp…er…MySQL. It’ll do work that you
could never do on your own, and it’ll do that work tirelessly and quickly.
Note This book periodically recommends other books, covering topics that are too specialized or tangential
for a manual about PHP and MySQL. Careful readers may notice that not every one of these titles is published
by Missing Manual parent company O’Reilly Media. If there’s a great book out there that doesn’t happen to be
published by O’Reilly, this book will still let you know about it.
PHP & MySQL: The Missing Manual is designed to accommodate readers at every
technical level. The primary discussions are written for advanced-beginner or inter-
mediate Web authors and programmers. Hopefully, you’re comfortable with HTML
and CSS, and maybe even know a bit of JavaScript. But if you’re new to all this Web
stuff, take heart: special boxes called “Up to Speed” provide the introductory infor-
mation you need to understand the topic at hand. If you’re an advanced user, on the
other hand, keep your eye out for similar boxes called “Power Users’ Clinic.” They
offer more technical tips, tricks, and shortcuts for the experienced computer fan.
Introduction xv
About This
Author’s Note
Book Typing in a command-line editor is actually exactly how I work. But then, I’m a
dinosaur, a throwback to days when you had to watch commercials to see primetime TV, and you’d miss emails
because your pocket didn’t buzz every time your boss whisked you a command through the ether.
Today, for most of you, a good text editor and a good graphical FTP client are much better choices. Seriously, my
addiction owns me, and I so badly want to :wq! it.
Chapter 1 will point you at several great editors, and the fancier ones will have FTP
built right in. But a program like Cyberduck (www.cyberduck.ch) is great, too. You
can write a script, throw it online, and test it all with a few mouse clicks. So go ahead
and get that FTP program downloaded, configured for your web server, and fired
up. You’re gonna need it.
Missing CD
This book doesn’t have a CD pasted inside the back cover, but you’re not missing
out on anything. Go to www.missingmanuals.com/cds/phpmysqlmm to download
code samples, code samples, and also, some code samples. Yup, there are a lot of
them. Every chapter has a section of code for that chapter. And you don’t just get
completed versions of the book’s scripts. You’ll get a version that matches up with
each chapter, so you’ll never get too confused about exactly how your version of a
script or web page should look.
And so you don’t wear down your fingers typing long web addresses, the Missing
CD page also offers a list of clickable links to the websites mentioned in this book.
Registration
If you register this book at oreilly.com, you’ll be eligible for special offers—like discounts
on future editions of PHP & MySQL: The Missing Manual. Registering takes only a few
clicks. To get started, type www.oreilly.com/register into your browser to hop directly
to the Registration page.
Feedback
Got questions? Need more information? Fancy yourself a book reviewer? On our
Feedback page, you can get expert answers to questions that come to you while
reading, share your thoughts on this Missing Manual, and find groups for folks who
share your interest in PHP, MySQL, and web applications in general. To have your
say, go to www.missingmanuals.com/feedback.
Errata
In an effort to keep this book as up-to-date and accurate as possible, each time we
print more copies, we’ll make any confirmed corrections you’ve suggested. We also
note such changes on the book’s website, so you can mark important corrections
into your own copy of the book, if you like. Go to http://tinyurl.com/phpmysql-mm
to report an error and view existing corrections.
Introduction xvii
Safari® Books
Online Safari® Books Online
Safari® Books Online is an on-demand digital library that lets you
easily search over 7,500 technology and creative reference books
and videos to find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library
online. Read books on your cell phone and mobile devices. Access new titles before
they are available for print, and get exclusive access to manuscripts in development
and post feedback for the authors. Copy and paste code samples, organize your
favorites, download chapters, bookmark key sections, create notes, print out pages,
and benefit from tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have
full digital access to this book and others on similar topics from O’Reilly and other
publishers, sign up for free at http://my.safaribooksonline.com.
Chapter 1:
PHP: What, Why, and Where?
Chapter 2:
PHP Syntax: Weird and Wonderful
Chapter 3:
MySQL and SQL: Database and Language
chapter
1
PHP: What, Why,
and Where?
P
HP is ultimately text, taken by your web server and turned into a set of commands
and information for your web browser. And because you’re just working in text,
there’s not a lot you have to do to get going as a PHP programmer. You need to
get familiar with PHP itself—and the best way to do that is to install PHP on your own
computer, even though most of your programs will run on a web server.
Then, you need to run an actual script. Don’t worry; it’s amazingly easy to write your
first program in PHP, and you’ll end up writing more than just one program before
you hit Chapter 2.
And through it all? You’ll begin taking control. PHP gives you the ability to be an
active participant in your web pages. It lets you listen carefully to your users and
say something back. So get going; no reason to leave you users with passive HTML
pages any longer.
3
Gathering and best tools for writing PHP code are also free. All you need is your own copy of
Your Tools the PHP language on your computer, plus a plain old text editor. This section shows
you where to find them.
PHP on the PC
PCs come with a lot of software pre-installed. Unfortunately, one program that most
PCs don’t come with is PHP. That’s okay though: you can get PHP up and running
in just a few minutes, as long as you have an Internet connection.
Note If you have a Mac, you don’t have to go through this installation process. Flip to page 9.
Open up your favorite Web browser and head to www.php.net. This site is PHP’s
online home, and it’s where you’ll download your own version of the PHP language,
along with all the tools you need to write and run PHP programs. Look along the
right side of the PHP home page for the Stable Releases heading; you can see it on
the right of Figure 1-1.
Figure 1-1
If you ever want to
download a new version
of PHP—or update the
version you’ve already
got—then www.php.net is
the place to visit.
Click the link for the version with the highest number. (For more information on what
all these versions mean, see the box on the next page.)
Figure 1-2
The PHP site always has
at least the latest stable
version, and the previous
stable version available
for download. Unless
you’ve got a really good
reason to do otherwise,
always go with the latest
stable version.
UP TO SPEED
Figure 1-3
PHP has a page dedicated
to Windows downloads.
There are still a lot of
options, but don’t get too
distracted by so many
choices. You’re looking for
a single word: Installer.
Just look for the Installer option and click the link. The installer is usually a big
download, but includes a nice Windows installer that will make getting PHP running
a breeze. Click this link and then grab a cup of coffee while you’re waiting for your
download to complete.
Note If you’re thinking you could have just gone directly to http://windows.php.net/download/ , then you’re
right: You could have. But six months from now, you may forget that longer URL, but remember www.php.net. On
top of that, a good old-fashioned Google search for PHP takes you to www.php.net, so it’s a good idea to learn
how to get to the Windows installer from the main PHP home page.
Once your download’s done, find the downloaded file and double-click it. When
Windows asks for permission to run the installer, click Allow, and then click Next on
the pop-up screen to start the installation.
You’ll have to accept a license agreement and then select an installation directory.
Go with the suggested C:\Program Files\PHP\ , so you can always find PHP with all
Figure 1-4
If you want to install a local web server to test
your entire web applications on your machine,
select the IIS FastCGI or Other CGI option. But for
getting started, “Do not setup a web server” is
the simplest option.
Figure 1-5
The Windows installer comes with the basic PHP
installation, but you can also add several extras,
which you can access by clicking the white box
next to Extras and selecting individual features.
Finally, click Install and then let your progress indicator march to full. That’s it! You’ve
got PHP running on your machine.
To check out PHP, go to your Start menu and type cmd in the Search box. A command
window opens, into which you can type commands like those that run PHP. Go ahead
and type php, as you see in Figure 1-6.
Even though it doesn’t look like much, that blank line and empty command prompt
mean PHP is installed correctly. Now you’re ready to get into your first program.
Figure 1-6
You won’t spend a lot of
time running PHP from
the command prompt,
but it’s a nice quick way
to test things out. The
Windows installer makes
sure you can run PHP
from anywhere on the
command line, from any
directory.
Warning Shift-c-A works only if your desktop or another file folder is active. If you’re currently viewing
this book in an e-reader or online, for example, click your desktop and then press Shift-c-A.
Figure 1-7
The Utilities folder
hides all sorts of useful
programs that come with
Mac OS X. Look around,
as there are all sorts of
goodies you may want to
use regularly.
Figure 1-8
The Terminal program lets
you use a command line
on Macs. A lot of your PHP
coding will be done using
Terminal, so you’ll get
used to this application
pretty quickly.
Tip You’ll often use the Terminal application for testing out your PHP programs before you upload them to
your server. To make it easier to launch Terminal, you may want to drag the icon into your dock so you can quickly
launch Terminal in the future.
Double-click the Terminal icon, and you’ll see a white rectangular screen with a little
black cursor blinking, as in Figure 1-9. That little cursor is going to be one of your
best friends on your journey to PHP nirvana.
Figure 1-9
When you first open Terminal, you
won’t be too impressed. You’ll get
a line that probably matches your
computer’s name, and then a weird
dollar sign. Don’t worry—this will all
soon be old hat.
To make sure PHP is installed on your system, just type php, all in lowercase letters,
and hit Enter. Unfortunately, the way to know things are working is if you don’t see
Hit Control-C to stop that single eye from staying, and you’ll get a blinking cursor
again. This time, type which php. The which command tells you where on your
computer the program you give it is located—php in this case. You’ll probably get
something back that looks like Figure 1-10; here, php is in the /usr/bin directory.
You’ll probably get a similar result.
Figure 1-10
Lots of the programs you use in
Terminal are scattered around
your Mac’s hard drive. The which
command lets you know exactly
where a command really resides on
your machine.
Once you’ve seen exactly where php is, you’re ready to go!
Figure 1-11
NuSphere PhpED gives
you a ton of features,
and supports JavaScript,
CSS, and HTML, as well as
PHP. It’s also got great
documentation for most
of the PHP functions and
libraries.
If you’re on a Mac, then the two leading candidates for editors that do text plus lots
of other cool things are BBEdit (www.barebones.com/products/bbedit/index.html)
and TextMate (www.macromates.com). Both are Mac-only programs, and both offer
similar features to what PhpED offers on Windows: color-coding, file management,
help documentation, and support for HTML, CSS, JavaScript, and a lot more. You can
see BBEdit in action in Figure 1-12; you’ll need to drop $100 to get going with BBEdit.
You can see what TextMate looks like in Figure 1-13. It looks a little simpler than
BBEdit, and if you’ve never used a programming editor, it might be a little easier to
begin with. It’s going to cost you about $60, slightly less than BBEdit.
Figure 1-12
BBEdit is supposed to be
bare bones, but you’ll
find it’s got more than
adequate PHP support.
It’s tuned primarily for
HTML, so there are a few
oddities, but it’s a great
choice for PHP work on
the Mac.
Figure 1-13
TextMate is an editor that
seeks to provide color-
coded editing and not
much else. It does offer
file management and FTP
support, but it’s best at
letting you type code and
staying out of the way.
Note Once you’ve become familiar with PHP, you can also check out Eclipse PHP ( www.eclipse.org/
projects/project.php?id=tools.pdt). The Eclipse IDE has long been a favorite for Java developers, and there are
now enough plug-ins for PHP that it’s a legitimate option for PHP programmers, too. However, there’s a lot going
on in Eclipse—tons of tools and gadgets—so you might want to wait a bit before you dive head first into Eclipse
PHP. Come back to it later, though; it’s well worth checking out.
echo "\nThanks, " . $name . ", it's really nice to meet you.\n\n";
?>
A lot of this code may look weird to you, and that’s OK. You’ll understand every bit
of it soon. Right now, just get used to looking at PHP, which is quite a bit different
from HTML or JavaScript.
Warning Some of the editors you might use, like TextEdit, automatically create rich text documents.
Rich text lets you use formatting, like bolding and underlining. You don’t want that in your PHP code, so look for
the option to use plain text, which doesn’t allow formatting.
If you’re using TextEdit, choose Format➝Make Plain Text. You won’t have that option if you’re already typing in
plain text. If you’re using Notepad, rich text isn’t an option, so you’ve got nothing to worry about.
Figure 1-14
PHP is just text, but it’s got several weird characters.
You’ll want to start getting used to typing the dollar
sign ($), angle brackets (< and >, just as in HTML), and
the backslash (\). You’ll be using those characters a
whole lot.
Note Most programs on Windows and the Mac will supply you a default extension, like .txt. Make sure you
replace that with .php. Windows especially tends to hide extensions, so make sure your full filename is sayHello.php,
not something like sayHello.php.txt.
Figure 1-15
You can get to the TextEdit preferences under the Prefer-
ences menu, or with the shortcut combination c-,. In the
Preferences box, you’ve got lots of options, but the text
format and font used for plain text are the most important
for now.
Figure 1-16
Eventually, you’ll run most of your
PHP scripts through a web browser.
For now, though, the command line
lets you take control of the php com-
mand and give it a particular script
to run, and then see the output on
the command line.
That’s it! Your first program works, and you’re ready to go deeper into PHP.
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example">Example 1-1</div>
<div id="content">
<h1>Welcome!</h1>
<p>Hello there. So I hear you're learning to be a PHP programmer!</p>
<p>Why don't you type in your name for me:</p>
<form action="scripts/sayHelloWeb.php" method="POST">
<p>
<div id="footer"></div>
</body>
</html>
Note You can download this HTML, along with the rest of the book’s sample files, from www.missingmanuals.com/
cds/phpmysqlmm. You can also get the CSS and images used by the samples, which let you give your programs a little extra
visual pizzazz. Still, especially as you’re just getting started, you’ll learn a lot more if you’ll type in the PHP code for these
programs yourself.
Almost nothing about this page should be new to you. All it does is reference an
external CSS style sheet, provide a text greeting like sayHello.php did, and then
define a form into which users can type their names.
The only thing that should have caught your attention is this line, in the form
definition:
<form action="scripts/sayHelloWeb.php" method="POST">
This code means that your form is going to submit its information to a program
called sayHelloWeb.php, a new PHP program you’re about to write. Once the form
is submitted, sayHelloWeb.php takes over and prints out the welcome message.
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example">Example 1-1</div>
<div id="content">
<div id="footer"></div>
</body>
</html>
Save this program as sayHelloWeb.php, and be sure you’ve got your file in plain
text with the right extension.
The first thing you probably noticed here is that this file looks a whole lot like HTML.
In fact, compared to sayHello.php, the first PHP program you wrote, this version
might look like a style of programming that’s a lot easier to learn. That’s because
once you’re using PHP to work and interact with web pages, a lot of what your PHP
programs will do is insert data into existing web pages, which means you’ll be work-
ing with HTML a lot. Of course, that’s great news, because you already know HTML,
so you’ll be adding to what you know, rather than learning something completely
new from scratch.
Once you realize that a lot of this program is just HTML, you can probably already
guess what a lot of this program does. Here’s a section-by-section breakdown:
• The page starts out with a normal html element and head section.
• The body section begins, and sets up the page heading and example number,
just like the regular HTML page, sayHello.html.
• The page defines a heading with h1, and prints “Hello,.“
• The <?php tells the browser some PHP code is coming. Then, then $_REQUEST
variable is accessed, and a property called name within that variable is printed
using echo.
• The end of the PHP code is indicated with ?>.
• The rest of the HTML is output, just as in sayHello.html.
This program, like most PHP programs you’ll write, accepts its input from a web
page, either from one built in HTML like the pages you’ve created before, or from
another PHP program. It’s the job of that web page—sayHello.html in your case—to
get the user to enter her information, and then send that information on to this
program. The information from that HTML page is stored in $_REQUEST, which is
a special variable in PHP.
Variables Vary
A variable in PHP, or any other programming language, is something that stores a
value. Variables have names, and in PHP, those names can be almost anything you
Note Technically, the name of a PHP variable does not include the $, but most PHP programmers consider
that $ a part of the variable itself. So you’ll hear PHP programmers say things like “dollar my height” instead of
just “myHeight” to refer to $myHeight.
Variables are not just names, though. They also have a value. So the value of
$myHeight might be the number 68 (for 68 inches) or the text “68 inches.” In
PHP, though, you’re not stuck with that value forever. You can change the value
of a variable, which is where the word variables actually comes from: a variable
varies, or changes.
In sayHelloWeb.php, you’re using the special PHP variable $_REQUEST to get the
user’s name, which he entered into the form you built in sayHello.html. PHP gives you
the ability to get to anything a user entered into a form using $_REQUEST and the
name of the form entry field—in this case, “name.” So $_REQUEST['name'] returns
the information a user put into a web form, specifically into an input field called
“name.” If the user also entered in their phone number, say, into a form field called
“phoneNumber,” you could get that value in PHP with $_REQUEST['phoneNumber'].
Note It’s okay if you’re still a little fuzzyon the details of how variables and $_REQUEST work. You’ll learn
a lot more about variables and in particular special variables in PHP like $_REQUEST in the next few chapters.
Once your PHP program grabs the value from the “name” form field, it prints that
value out using echo, something you’ve already used in your first PHP program. That
value gets dropped right into the HTML sent back to the browser…something you’ll
want to check out for yourself by running your new program.
Note You don’t have to organize things this way, but if you do, all the examples you download for this book
will work without any changes. If you do change this directory structure, you’ll need to change all the references
in your HTML and PHP to CSS, JavaScript, and other PHP programs.
Now that you’ve got your HTML and PHP ready, you need to upload those files to
the right directories on your web server. You should also download phpMM.css from
the book’s website at www.missingmanuals.com/cds/phpmysqlmm, and get the
CSS in the right place as well.
Once you’ve got everything in place, your web server directory structure should
look something like Figure 1-17.
Figure 1-17
The HTML and PHP files you
created are specific to this
chapter, so they belong in
ch01/. But phpMM.css is for
all the book’s examples
you’ll be building, so put
it in css/ under the root of
your web server.
Figure 1-18
More often than not, you’ll
access an HTML page rather
than a PHP program directly.
But those HTML pages will
use your PHP programs to
generate responses to your
users’ requests.
Figure 1-19
The web browser
doesn’t actually run your
program. Instead, it asks
your server to run the
program, and that server
then gives the result of
running sayHelloWeb.
php back to the browser,
which shows you a
personalized welcome
message.
It may seem like you’ve done a lot of work just to have a web browser tell you your
name. In fact, you could probably write the same program in JavaScript if you
wanted. But now that you’ve created a few PHP programs, you should already see
how easy it is to write this sort of code.
And before you know it, you’ll be doing a lot more than telling users their names.
You’ll be talking to a database, doing advanced calculations, making decisions based
on information the user gave you and what you have stored in a database, and more.
But it all begins with a little HTML, a PHP program like the ones you’ve just written,
and the directory structure you’ve got in place.
2
PHP Syntax: Weird
and Wonderful
Y
ou’ve got a couple of PHP programs running, and one of them even works
with an HTML form. But so far, you’ve just been typing code. Even though
you’ve just gotten started with PHP, you’re ready to dig deeper, and start to
understand what’s going on in that code. In this chapter, you’re going to get com-
fortable with a lot of the PHP syntax: that means learning what special words you
type into your programs, and what each one of those special words—usually called
keywords—tells PHP to do.
Fortunately, this learning doesn’t mean you can’t still build interesting programs that
run in a web browser. In fact, since almost everything that’s done with PHP involves
Web pages, all your scripts in this chapter will accept information from a Web form
and work with that information. So you’re not just learning PHP; you’re learning to
write Web applications.
You may remember that $_REQUEST is a special PHP variable that lets you
get information from a web request. You used it to get one particular piece of
information—the user’s name—but it can do a lot more.
25
Get
Information
from a Web Access Request Parameters Directly
Form
In fact, to see just how handy $_REQUEST really is, open up your text editor. Type
the code below, in which a visitor enters her name and several other important bits of
contact information, like her Twitter handle, Facebook page URL, and email address.
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example">Example 2-1</div>
<div id="content">
<h1>Join the Missing Manual (Digital) Social Club</h1>
<p>Please enter your online connections below:</p>
<form action="scripts/getFormInfo.php" method="POST">
<fieldset>
<label for="first_name">First Name:</label>
<input type="text" name="first_name" size="20" /><br />
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" size="20" /><br />
<label for="email">E-Mail Address:</label>
<input type="text" name="email" size="50" /><br />
<label for="facebook_url">Facebook URL:</label>
<input type="text" name="facebook_url" size="50" /><br />
<label for="twitter_handle">Twitter Handle:</label>
<input type="text" name="twitter_handle" size="20" /><br />
</fieldset>
<br />
<fieldset class="center">
<input type="submit" value="Join the Club" />
<input type="reset" value="Clear and Restart" />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>
Tip For more information on how HTML is used in this code, see the box below.
Save this file as socialEntryForm.html. To make sure your HTML is just the way
you want, go ahead and upload it to your server, in the ch02/ directory. Make sure
you’ve got the book’s CSS in the right place—under css/ in your server’s root—and
then open a browser and head over to your HTML form. You should see something
like Figure 2-1.
In sayHelloWeb.php, you used $_REQUEST to get submitted form information, and
then asked specifically for the “name” value. But with this new form, there’s a lot
more information being sent from the form.
To get all that information, you need to create a new script called getFormInfo.php,
and enter in this code:
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<div id="content">
<p>Here's a record of what information you submitted:</p>
<p>
First Name: <?php echo $_REQUEST['first_name']; ?><br />
Last Name: <?php echo $_REQUEST['last_name']; ?><br />
E-Mail Address: <?php echo $_REQUEST['email']; ?><br />
Facebook URL: <?php echo $_REQUEST['facebook_url']; ?><br />
Twitter Handle: <?php echo $_REQUEST['twitter_handle']; ?><br />
</p>
</div>
<div id="footer"></div>
</body>
</html>
Figure 2-1
This web form is a pretty
typical entry page for a
user to fill in. But what
happens when this form
gets submitted? You’re
about to find out, and in
fact, take control of all
this entered information.
You can already see what’s going on here. In addition to grabbing the value of the
“first_name” and “last_name” fields—similar to getting the value of the “name”
field in sayHelloWeb.php—you’re using $_REQUEST to pull in the values the user
entered into the other form fields.
Go back to your web form, and enter your information. Then submit the form, and
you should see the result of getFormInfo.php running. Your browser should show
you something like Figure 2-2.
In fact, this is the way you’ll use the $_REQUEST variable in most of your PHP
programs:
echo $_REQUEST['FORM_INPUT_FIELD_NAME'];
Figure 2-2
Almost everything in PHP
begins with some piece of
information submitted via
either an HTML Web form
or another PHP script.
With this chunk of code in mind, go back to your new program, getFormInfo.php.
Instead of just using echo to print out the submitted information, store each piece
of information in a variable. Then you can use that information however you want,
and as many times as you want.
<?php
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
$facebook_url = $_REQUEST['facebook_url'];
$twitter_handle = $_REQUEST['twitter_handle'];
?>
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- Existing HTML code -->
</body>
</html>
Notice that you can create blocks of PHP code—beginning with <?php and ending
with ?>—anywhere you want. In this script, there’s currently a block of PHP before
any HTML, and then several small blocks of PHP within the big chunk of HTML. It’s
really up to you when and where your PHP goes, as long as it gets the job done.
You could have put this block of PHP between the page’s opening html and head
element, or between the head and the body elements; that choice is up to you.
Note Just because you can do something doesn’t mean you should. It’s usually best to do as much of your
PHP work as you can before you output any HTML, and then output as much of your HTML as you can in a single
place. This system keeps most of your code in one place, and most of your HTML in another place. (For more advice
on why it’s important to keep your code well organized, see the box on page 32.)
Of course, you’ll still have lots of times when you insert PHP into your HTML, as in getFormInfo.php, and that’s
okay. Those little bits of PHP fit into the HTML, and certainly don’t mix things up as much as 20 or 30 lines of PHP
stuck in the middle of your HTML.
Ende.
INDHOLDSFORTEGNELSE.
Side
»S. M.« 1
Hölandsslaget 21
En Norges Søn 47
Før Stormen 65
Fra Bjørnehien 77
Brændetyven 95
Hjemmets Fugl 111
Store Torsken! 127
Visen 143
Spionen 163
Et falsk Signal 183
Klokkeren fra Id 199
Ole Svendsens Død 215
Colbjørnsens »brogede Karle«
235
Stormuglen 253
Skjændselsbarnet 271
Ildskriften læses endnu paa
Krønikens evige Tavle 291
Det brænder, han render —
Ritsch! 309
Mari Bjørnstad 335
I Løbegraven 347
Den store Fred 369
FODNOTER.
[1] En Klove er en liden Sænkning mellem to Bjerge.
[2] Præsten, Hr. Peder Rumohr, der havde tjent som Cornet under
Hertugen af Würtemberg mod Jacob Stuart, gjorde sig velfortjent
under Kong Carls Indfald i Norge, idet han listelig forledede
General Aschenberg ved falske Rygter til at trække sig tilbage
over Grændsen og saaledes væsentlig bidrog til, at
Nordmændene sloge det svenske Parti paa Mors, hvor bl. a. Kong
Carls Krigskasse fandtes, og hvor Fjenden mistede 300 Mand. Da
Kong Carl med uforrettet Sag drog sig tilbage fra Christiania, lod
han Præsten overrumple og slæbe med i Fangenskab til Sverig,
hvor han efter to Aars Lidelser døde af Skjørbug og Vattersot,
»saasom han meest spiste Drøvelsens Brød.« Efter sit Ønske fik
han til Begravelsestext Job 3. v. 18: »Der have Fangerne Frihed
tillige; de høre ikke Trængerens Røst.«
[3] Carl den Tolvte kunde endnu, hærdet ved Legemsøvelser og
Faste, iført Rytterstøvler, lægge sin Fod bag Øret, paa Hesteryg.
[4] Carolinere kaldtes de faa graanede og hærdede Krigere, der
havde overlevet Carl den Tolvte og hans Krigstogt.
[5] Forfatterens Svigermoder var en høitbegavet Dame, Søster til
den bekjendte norske Maler, August Cappelen, hvis Malerier
findes i Christiania Nationalgalleri.
[6] Dr. C. Palludan-Müller er i sine udmærkede, skarpsindige,
kritisk-historiske Undersøgelser kommen til det Resultat, at Kong
Carl efter al Sandsynlighed maa være faldet for et Projectil fra
Fæstningen.
[7] Det er et karakteristisk Kjendetegn for det stærke Indtryk,
som denne tragiske Begivenhed gjorde paa Øienvidnerne, at flere
af disse og blandt dem Siquier i Vildelse senere hen beskyldte sig
selv for at have myrdet Kongen, hvilke Tilstaaelser dog klart er
beviist kun skyldes Hallucinationer. De senere militaire og
sagkyndige Undersøgelser, der fandt Sted paa selve
Gjerningsstedet saavelsom paa Liget, have tilstrækkelig klargjort,
at ikke Skygge af Mistanke om en slig Niddingsdaad, som dette
Kongemord vilde være, klæber ved den tapre og hæderlige
svenske Nation.
[8] Denne Orden har existeret i Frederikshald, traadte dog først
ud i Livet 1ste Januar 1750. Ordenstegnet var da en Triangel,
hvilken var forfærdiget af Guld, som det ædleste og reneste af
Metallerne, for at tjene dem, som dermed beæredes, til en
bestandig Paamindelse »altid at kultivere de ædle og uforfalskede
Dyder, hvormed den er erhvervet«. Paa den ene Side er graveret
disse Ord: »l'ordre de la constance, institué par les dames à
Frederikshald le 9me Decbr 1749.« Paa den anden Side staaer
disse Ord: »Dedié au vrai mérite en dépit des franc Maçons.« Den
bæres udi et blaat, vatret Baand Couleur d'azur og bindes med en
dobbelt Sløife i det tredie Knaphul af Vesten. Den første Mand,
der udmærkedes med denne Orden, var Rudolph de Romeling,
Kgl. Mayst. bestalte Major.
[9] Colbjørnsens Hustru var drikfældig og letfærdig.
Afskriverens rettelser
s. 4: rødere, hendes Blik[Bllk] fik et spændt Udtryk.
Morgenvinden
s. 9: Hun vil ikke tage det ilde op, naar hun hører, vi[v]
s. 11: hendes Ansigt [i] Bukler og Krøller, over hvilke en
saakaldet Fontange
s. 34: at vi ikke fik hende grundig forhørt[førhørt]. — Skal vi
gjøre
s. 50: sløv og følelsesløs[følesløs]? — Javist, Hustru!« udbrød
Bjørnstad
s. 52: Hver Nordmand[Normand], som vil norsk
Retfærdighed fuldt ud
s. 52: Som Bjørnstad stod dèr[dér] i blodfuld Kraft, mens
s. 72: »Kan Skipper Daniel[Daniels], der er en saa forfaren
Mand,
s. 73: »Ja, svar paa det, Daniel[Daniels],« raabte en mager
s. 73: Deres beredvillige Tjener bevise, at det, Skipper
Daniel[Daniels]
s. 74: Skipper Daniel[Daniels] slog en Latter op, der
skingrende
s. 91: som[sam] ham dèr« — han nikkede over mod
s. 91: som ham dèr[dér]« — han nikkede over mod
s. 98: Aschenberg[Asheberg] ved Herrebroen havde maattet
lade sine Folk
s. 99: reiste sig paa Thinge og sagde til svenske
Kong[Konge] Oluf:
s. 106: Syne i Huulveien; deres Karabiner lyste i
Maaneskinnet[Maaneskinnnet],
s. 119: Lidt efter skjød Jørgen sit Arbeide[Arbejde] fra sig og
s. 124: Hvad Ret havde han vel til [at] beklage sig? Han
s. 138: mod Bjørnstads[Bjønstads] Gaard.
s. 159: hviskede Månsson; »det er Dødsdeliriet[Dødsdellriet],
som kriller i
s. 184: Carl[Karl] den Tolvte forsmaaede Tidens
Allongeparyk.
s. 208: »Alt er i Orden, Hr. Stadskapitain[Stadskaptain],«
meldte
s. 222: Jeres[jeres] Folk. Skipper Daniel var her i Møllen for
en
s. 229: Skoven og indjog Folkene den Tanke, at de bleve
forfulgte[for fulgte]
s. 247: »Du tilraaber dem »Holdt! — hvem dèr[dér]?« og
naar
s. 252: hvor Musketild og Kanontorden[Kanontordenen]
ledsagede
s. 257: Aar havde bragt frelst i Land, og Brovagten i
Frederikshald[Frederederikshald]
s. 261: der saa lyst anden Gang for Bager Hans
Høyer[Hoyer] og
s. 269: Gevær blev afskudt[sfskudt]. Thi da de vare komne
Fjenden
s. 276: Paa Hjørnet af Kirke- og
Borgerskandsegade[Borgerskandsgade] laa
s. 278: »Enkemadam Anea Høyer[Höyer], alene! Kommer
ikke
s. 280: og raadslaa[raaslaa] med hverandre om at stikke vor
By i
s. 280: det at have Hjerte i Brystet at ville stege sine[sin]
Medskabninger
s. 300: som vi forlode i Ulle Halvorsens Kviststue i
Walcks[Walkers]
s. 303: Tvangsægteskabet, Lysningen i Luneland[Lumeland].
Han blev
s. 307: »Jeg er kun en[et] af Norges ringeste Døtre,«
hviskede
s. 316: hjem langveis[langsveis] fra. »Ilden skal slukkes.
Dirigeer
s. 317: sig i Walcks[Walkers] Gaard, gik Spisesalsdørene op
til Maiestætens
s. 336: holde Øie med Nordmændene[Normændene] og
svække deres Modstandskraft
s. 350: syntes saaledes at have været[være] forgjæves og
deres By
s. 353: mod det Sted, hvor Arbeidet[Arbejdet] med de nye
Linier skulde
s. 362: var dræbt af en ubekjendt[uebkjendt] Haand.«
s. 363: Fødder. General Schwerin havde stillet[sfillet] Vagt i
Løbegraven,
s. 363: Da dette var varetaget, vendte Siquier[Sequier] sig til
s. 365: intet undtagen Gustav Adolphs[Adolps] Portrait og
Bønnebog.
s. 374: den skyder sig frem, beriget ved utallige
Vandaarer[Vaandaarer]
s. 374: Midt i al denne Travlhed fløi Faster[Fasters] Ellens Blik
s. 385: disse Ord: »Dedié au vrai mérite[mêrite] en dépit des
franc Maçons.«
s. 392: der afdæmper for stærke Strengelyde[Strengelyd] i
sit stormende
s. 392: blev knuust af et Kølleslag fra oven[fraoven].
*** END OF THE PROJECT GUTENBERG EBOOK BJØRNEÆT:
NATIONALHISTORISK ROMAN ***
Updated editions will replace the previous one—the old editions will
be renamed.
ebookbell.com