TweetFollow Us on Twitter

PHP, MySQL, And Forms

Volume Number: 21 (2005)
Issue Number: 8
Column Tag: Programming

Getting Started

by Dave Mark

PHP, MySQL, And Forms

In our last PHP/MySQL exploration, we used the MySQL monitor to build a database, create a new table, then populate the table with data. We did use our PHP chops to query the table and spit out some HTML with the results, but that's a pretty bare-bones/hard-coded approach. A more common technique is to use an HTML form to populate the table. For example, suppose you were building an order-entry system for your sports memorabilia shop. You could use the MySQL monitor to enter all the data that represents your inventory. If you are really comfortable with the monitor, that's not a terrible approach. But, what if you want your assistant, who is a whiz at the web but has no MySQL experience, to manage the data? Creating a series of HTML-driven forms is definitely the way to go.

Before we dig into this month's sample code, I'd like to take a momentary detour to talk about a terrific new book I just got.

Hacking Mac OS X Tiger

Back in the early days of Macintosh, there were just a very few Mac programming titles. One of the best of these books was called Macintosh Programming Secrets. Written by Scott Knaster and Keith Rollin, the book quickly became a cult classic. Well, Scott is back and his latest book is every bit as cool as Macintosh Programming Secrets. The long title is Hacking Mac OS X Tiger: Serious Hacks, Mods, and Customizations. This is no idle boast. The book is chock full of wonderful insider info, and is just plain fun.

The book starts off with a collection of tips. For example, try holding down the option key, then pressing the volume up (or down) key on your keyboard. Cool! The Volume System Pref opens. There are tips for the Finder, the Dock, Dashboard, System Prefs, iTunes, and a lot more. To me, the book is worth the price of admission just for that part along. But wait, there's more!

The second part of the book is called Mods, and explores more developer-oriented things. Things like Automator, Xcode, Property Lists, and Application Bundles. Lots of great info here, especially if you are relatively new to Mac development.

The third part of the book might be my favorite. It's called Hacks, and is full of, well, um, hacks! You'll customize dock icon behavior, hack some Dashboard widgets, even redirect your web cam output to create a live video desktop.

All this stuff is presented in Scott Knaster's witty, irreverent style. I totally love this book! Hacking Mac OS X Tiger is part of Wiley's ExtremeTech series. You can find it at:

http://www.wiley.com/WileyCDA/WileyTitle/productCd-076458345X.html

And now back to our regularly scheduled programming...

Implementing a Form with PHP

The key to implementing an HTML form is the <form> tag. Typically, the <form> tag will include both action and method attributes. The action attribute specifies the name of the file to which to send the form's results. The method attribute specifies how form data is passed along to the action recipient and is either GET or POST. The primary difference between GET and POST is that GET causes the form data to be embedded in the action's URL, while POST passes the data to the action as an input stream (via stdin, for example). GET forms can be bookmarked, since the data is embedded in the URL. POST forms cannot be bookmarked.

In general, I use POST as my default unless I specifically need a URL to be bookmarkable. You've undoubtedly clicked on your browser's reload button and been asked, "Do you really want to reload this form?" or something similar. The page in question is a POST request.

Good to know the difference between GET and POST, use whichever works best in any situation. Note that GET is the default. Note also that if your form contains passwords and the like, the GET URL will include the password data. Not a great idea if you will be passing the URL around.

Embedded between the <form> and </form> tags is the form content. The form content is made up of HTML formatted text, along with a variety of <input> tags. Each <input> tag represents an HTML form element, such as a popup menu, text field, non-echoing text field (for entering passwords), checkbox, radio button, submit button (a pushbutton whose purpose is to submit the form) or a reset button (a pushbutton used to clear the form).

An example will make this a bit clearer.

A PHP Form Example

This example puts up a pair of text fields, with appropriate labels. One field is a standard text field, the second a non-echoing text field. We'll use the former to enter your name and the latter to enter a password. We'll end the form with a submit button. When the submit button is pressed, the same page will be reloaded. The technique of taking two different actions on the same page of PHP code is a common PHP theme. While this is not a particularly useful example, it demonstrates this concept nicely.

Using BBEdit, or your favorite plain-text editor, create a new plain-text file and save it as php_form01.php, then type the following source code into the file:

 <html>
   <head>
      <title>Sample PHP Form</title>
   </head>
   <body>
      <?php
         if ( !empty( $_POST[ 'name' ] ) ) {
            echo "Your name is {$_POST[ 'name' ]}.<br />";
            echo "Your password is {$_POST[ 'pwd' ]}.<br />";
         }
      ?>
      <form action="<?php $PHP_SELF; ?>" method="POST">
         Name:
         <input type="text" name="name" />
         <br />
         Password:
         <input type="password" name="pwd" />
         <br />
         <input type="submit" />
      </form>
   </body>
</html>

Save the file and copy it into the Sites directory in your home directory. For example, I placed my copy of this code into /Users/davemark/Sites/.

Once this is done, fire up your favorite browser and enter this URL:

http://127.0.0.1/~davemark/php_form01.php

Be sure to replace davemark with your own user name. Also, be sure to keep the tilda (~).

Once you enter the URL, you should see results similar to those shown in Figure 1. If you don't, be sure your PHP server is running. To do this, create a new, plain-text file named test.php, fill it with these 3 lines of code:

<?php
phpinfo()
?>

Drag the test file into your Sites directory and type this URL into your browser:

http://127.0.0.1/~davemark/test.php

Remember to replace davemark with your user name. If the large PHP table appears in your browser, PHP is running and you've got an error in your version of php_form01.php. If the large PHP table does not appear, go back to the installation instructions for PHP and make sure your server is up and running.


Figure 1. The Sample PHP Form in action.

Click in the Name field and type your name. Next, tab over to or click in the Password field and type a password. Note that the password characters echo as dots. I'll show you why in a second.

Finally, click the Submit button. You should see something like the output shown in Figure 2. Notice that the name and password are both echoed and the form is then reloaded so you can try this again.


Figure 2. The name and password are echoed and the form is reloaded.

Let's take a look at the code, see how this works.

We start with the basic <html>, <head>, <title>, and <body> tags. Nothing new there.

<html>
   <head>
      <title>Sample PHP Form</title>
   </head>
   <body>

The first thing we do in the HTML body is open a PHP tag and jump into an if statement. The if statement calls the PHP function empty() to see if the variable $_POST[ 'name' ] is empty, that is, see if it has been set to a value.

Whenever you see a PHP function and don't know what it is, make your way over to http://php.net, type the function name in the search for text field, select function list from the in the popup menu, then click the arrow to do your search. The result of my search for the empty function is shown in Figure 3.


Figure 3. Searching for the empty function on php.net.

What the heck is $_POST[ 'name' ]? What a weird name for a variable. The variable $_POST is an associative array. An associative array is an array that is indexed by name instead of by numerical index. For example, you might have an array of nicknames for all your friends, where $nicknames[ 'Fred' ] is set to the string 'Stubby', while $nicknames[ 'Phil' ] is set to 'Scooter'.

Note that the quotes are optional for single word strings. So you might see $nicknames[ Fred ]. Though that will work, leaving out the quotes will make your code a bit more cryptic, so use them unless you find yourself in a funky situation where they just get in the way (quoted string inside another quoted string, for example). And even then, be sure to comment your code so everyone can follow along.

$_POST is an associative array that contains an element for each of your form's input fields. So $_POST[ 'name' ] contains the contents of the input element with the name "name". $_POST[ 'pwd' ] contains the contents of the input element with the name "pwd". You get the idea.

The goal of the if statement is to see if the name field is empty. If not, we'll use echo to display the contents of the name field. Want to learn about echo? Go to php.net and type echo in the search field, search the function list. About ? of the way down the page, you'll see a nice comment about using braces. This is worth reading. In a nutshell, you can use braces as separators when a space character just won't do. For example, in the code below, we used the braces to set off the name $_POST[ 'name' ] without putting a space between the end of the variable and the period. This lets us put a period immediately after your name.

Note that we included the <br /> HTML tag in our output. Remember, the PHP code spits out HTML as its output and then the HTML is passed back to the browser. The <br /> tag is used to put a return after the name and again after the password.

<?php
         if ( !empty( $_POST[ 'name' ] ) ) {
            echo "Your name is {$_POST[ 'name' ]}.<br />";
            echo "Your password is {$_POST[ 'pwd' ]}.<br />";
         }
      ?>

If the name field was filled, we'll already have printed the name and password before we get to this point. If the name field was empty, nothing will have been generated yet. Either way, we are now going to put up the form.

The <form> tag takes an action attribute and a method. We already know about the method. The action is the file you want served up with the results of your action. We could have created a second page that displayed the results of our form. But this self-referential approach is pretty common in PHP. We used the variable $PHP_SELF to have the form pass the results on to the same file, sort of like a function calling itself. Want to learn more about $PHP_SELF? It's not a function, so we'll need to search the whole site instead of just the function list. When you search all of php.net, you'll get a Google list of pages to look at. Here's a good place to start:

http://us3.php.net/reserved.variables

You'll need to search the page for PHP_SELF. Note that the $ is not part of the variable name.

<form action="<?php $PHP_SELF; ?>" method="POST">
         Name:

The two <input> tags specify a text field and a password field. Both do the same thing, but the password field echoes input as dots instead of the actual characters. Note that the name attributes of each <input> tag are what link the results to the $_POST associate array index.

   <input type="text" name="name" />
         <br />
         Password:
         <input type="password" name="pwd" />
         <br />

Finally, the last bit of <input> for the form is the submit button.

   <input type="submit" />
      </form>
   </body>
</html>

Type your name and password again and again. Each time you click submit, the page reloads, draws your name and password, and then redraws the blank form. Cool!

Adding MySQL to the Picture

Our next step is to add MySQL to the picture. We'll build a database, using the MySQL monitor, create a new table, then use the form we created to populate the database. If you are new to the MySQL monitor, go back June's Getting Started column for a review.

Fire up Terminal and start the MySQL monitor. As a reminder, I set up an alias for mysql:

alias mysql='/usr/local/mysql/bin/mysql'

Here's my sequence for starting MySQL, building the database, and building the table:

Daves-Computer:~ davemark$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 16 to server version: 4.1.12-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> create database myaccounts;
Query OK, 1 row affected (0.40 sec)

mysql> use myaccounts;
Database changed
mysql> create table passwords(
    -> name varchar(60),
    -> pwd varchar(60),
    -> userid int(10) auto_increment primary key );
Query OK, 0 rows affected (0.08 sec)

mysql> select * from passwords;
Empty set (0.09 sec)

In the above, I first created a database called myaccounts, set myaccounts as the current database, then created a table within myaccounts called passwords. Passwords contains a 60 character name, a 60 character password, and an auto-incrementing userid. We then verified that the passwords table was empty.

Let's switch back over to PHP and modify our code so we are writing our passwords into the table. Back in your plain-text editor, replace your existing code with this version:

<html>
   <head>
      <title>Sample PHP Form</title>
   </head>
   <body>
      <p>Connecting to the database...</p>
      <?php
         $host = 'localhost';
         $user = 'root';
         $pw = '';
         $db = 'myaccounts';

         $link = mysql_connect( $host, $user, $pw )
            or die( 'Could not connect: ' . mysql_error() );
         echo 'Connected successfully';
         mysql_select_db( $db );
      ?>
      <p>If we got here, we've connected!</p>

      <?php
         if ( !empty( $_POST[ 'name' ] ) ) {
            $tempname = $_POST[ 'name' ];
            $temppass = $_POST[ 'pwd' ];
            $query = "insert into passwords values ( '$tempname', '$temppass', 0)";
            $results = mysql_query( $query )
            or printf( "Query error: %s", mysql_error() );
         }
         mysql_close();
      ?>
      <form action="<?php $PHP_SELF; ?>" method="POST">
         Name:
         <input type="text" name="name" />
         <br />
         Password:
         <input type="password" name="pwd" />
         <br />
         <input type="submit" />
      </form>
   </body>
</html>

The first chunk of this code should be familiar from earlier columns. We use mysql_connect() to connect to the database and mysql_select_db() to make the database the current one for subsequent commands (just like use myaccounts; in the MySQL monitor).

<html>
   <head>
      <title>Sample PHP Form</title>
   </head>
   <body>
      <p>Connecting to the database...</p>
      <?php
         $host = 'localhost';
         $user = 'root';
         $pw = '';
         $db = 'myaccounts';

         $link = mysql_connect( $host, $user, $pw )
            or die( 'Could not connect: ' . mysql_error() );
         echo 'Connected successfully';
         mysql_select_db( $db );
      ?>
      <p>If we got here, we've connected!</p>

The next chunk of code looks like what we did earlier in the column. Instead of using echo to print out the form fields, we build a query instead and use mysql_query() to fire it off. This will insert the row into the MySQL table. It is important to note that the $query line is a single line of code. It wraps in this column, but you should enter it as a single unbroken quoted string in your source code.

After the if statement, we close the database. Each time this page is loaded, the data base is reconnected, worked with, then closed again. Some people put the mysql_close() at the very bottom of the file, just to make sure they don't accidentally place code beneath it.

   <?php
         if ( !empty( $_POST[ 'name' ] ) ) {
            $tempname = $_POST[ 'name' ];
            $temppass = $_POST[ 'pwd' ];
            $query = "insert into passwords values ( '$tempname', '$temppass', 0)";
            $results = mysql_query( $query )
            or printf( "Query error: %s", mysql_error() );
         }
         mysql_close();
      ?>

The rest of the code is pretty much the same as what you had above, the implementation of the form and the close body and html tags.

<form action="<?php $PHP_SELF; ?>" method="POST">
         Name:
         <input type="text" name="name" />
         <br />
         Password:
         <input type="password" name="pwd" />
         <br />
         <input type="submit" />
      </form>
   </body>
</html>

Running the MySQL Form

Let's take this puppy for a spin. First, be sure you saved your source code and copy the file to your Sites folder. In your browser, type this link:

http://127.0.0.1/~davemark/php_form02.php

Note that I saved this new version of the source code as php_form02.php. Be sure to change davemark to your user name.

Once the table loads, enter a name and a password (see Figure 4) and click the Submit button. Note that each time the page reloads, the database is reconnected.


Figure 4. Entering the data that will be written to the MySQL table.

Once you've entered enough data, go back to Terminal and take a look at your table.

mysql> select * from passwords;
+--------------------+----------------+--------+
| name               | pwd            | userid |
+--------------------+----------------+--------+
| Franklin Roosevelt | Delano         |    1   |
| Dave Mark          | fudgiethewhale |    2   |
| Dark Helmet        | spaceballs     |    3   |
+--------------------+----------------+--------+
3 rows in set (0.00 sec)

Cool! All the data is there.

Until Next Month...

There is just a ton you can do with MySQL and PHP. If you don't have a PHP library already, I found the books MySQL in a Nutshell and Programming PHP from O'Reilly and PHP 5 and MySQL from Apress a big help in getting started.

Not sure what I'm going to do for next month's column. I've been reading the galleys to Mark Dalrymple and Scott Knaster's upcoming Learn Objective-C from Spiderworks. Hmmm, might be fun to explore a bit of that. Well, we'll see. For now, it's back to Lake Anna for a bit more summer laziness. See you next month.


Dave Markis a long-time Mac developer and author and has written a number of books on Macintosh development. Dave has been writing for MacTech since its birth! Be sure to check out the new Learn C on the Macintosh, Mac OS X Edition at http://www.spiderworks.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.