PHP Tutorial: A n00b’s Guide To Making A Signup Form with PHP and WordPress
If you’re new to web development and want to learn how to create a simiple signup form with PHP and Wordpress, check out this PHP tutorial! By Ray Wenderlich.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
PHP Tutorial: A n00b’s Guide To Making A Signup Form with PHP and WordPress
20 mins
Creating the Beta Signup Database: Background
The next step is to create a table structure for our beta signup database. For the sake of this PHP tutorial, we’ll just record their name, email, and whether they’d like to be notified when the app launches. We’ll also add a few other columns to the table to make manual bookkeeping on the beta testers easier later.
Of course, we could just manually create our database using the mysql command line tool, but since we’re making this a WordPress plugin we may as well do things the WordPress standard way, which is to create the database tables upon initial plugin activation.
Again, WordPress makes doing this easy by providing a function we can call to register a callback for when the plugin gets activated. We can use it like the following:
register_activation_hook(__FILE__, array($battleMapBetaSignup, 'createDb'));
The first parameter is the path of the main plugin file. Well we only have one plugin file, so we just return __FILE__, which is the magic PHP constant for the pull path and filename of the current file.
One last piece of background we need to know before we get started. We all know that when you create database tables, it’s easy the first time: you just issue a CREATE TABLE statement.
But the tricky bit happens when you want to make changes to your database structure later. You can either drop the table and recreate it (hence losing any existing data inside), or make ALTER TABLE statements to modify your table and add the new rows, putting default values for any existing data.
Well, for WordPress plugins, in theory they can be upgraded by users at any time, so WordPress needed some kind of recommended solution for plugin developers for how to handle their table updates over time. They actually came up with a neat solution, by providing a function you can use named dbDelta.
dbDelta takes a CREATE TABLE statement, but rather than running the SQL statement directly, it takes a look at any existing table structure first. If there’s already a table there, it will alter the table automatically so it looks like the final desired structure, rather than dropping/recreating it. Cool eh?
So now that we have the background knowledge, let’s try it out!
Creating the Beta Signup Database: Implementation
Add the following code to the top of your MyBetaSignup class:
// Db version
public $dbVersion = "1.0";
function createDb() {
$installed_ver = get_option( "my_beta_version" );
if ($installed_ver != $this->dbVersion ) {
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$tableName = $wpdb->prefix . "my_beta_user";
$sql = "CREATE TABLE " . $tableName . " (
id mediumint NOT NULL AUTO_INCREMENT PRIMARY KEY,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
notify tinyint(1) NOT NULL,
selected mediumint NOT NULL DEFAULT 0,
responded mediumint NOT NULL DEFAULT 0,
udid varchar(255) NOT NULL DEFAULT \"\"
);";
dbDelta($sql);
add_option("my_beta_version", $this->dbVersion);
}
}
At the beginning, we make a variable to keep track of the current version of the database. This isn’t strictly necessary because dbDelta will take care of the upgrades, but this is a good practice that will make some upgrades in the future easier because we know where we’re coming from.
So we only bother creating/updating the database tables if the current version doesn’t match the version for this plugin. We then include upgrade.php, which is required to use the dbDelta function.
We create our table name by prepending the database prefix the user set up to our desired table name.
Then, we construct the create table SQL for our table. Note we keep track of the user the info will input (name, email, whether to notify) as well as some space for bookkeeping information we can use ourselves (whether they are selected, whether they responded with feedback, and what their UDID is). And of course we add an id to the table as well!
Finally we call the dbDelta function to run the SQL, and record the current version of our database.
To call this, just add the following to the bottom of your file:
register_activation_hook(__FILE__, array($myBetaSignup, 'createDb'));
Ok, let’s try it out! Go back to your plugins list in WordPress and deactivate and reactivate the plugin. If all went well, you should have a new database table in your WordPress database! You can check it out by checking out your new database tables with the mysql command line tool or an alternate method:
Creating the Signup Form
It’s about time to stop printing out Hello, World and start replacing it with an actual login form. To do this, replace your showSignupForm method with the following:
function showSignupForm($atts) {
if ($this->checkInput()) {
return "Coming soon!";
} else {
$form = '
<div class="my-form">
<form action="'.get_permalink().'" method="post">
<h3>Sign up for My Awesome Beta!</h3>
<p>
<label for="tester_name">Name:'.$this->required($this->testerNameError).'</label>
<input type="text" name="tester_name" id="tester_name" size="30"'.$this->getValue($this->testerName).'/>
</p>
<p>
<label for="tester_email">Email:'.$this->required($this->testerEmailError).'</label>
<input type="tester_email" name="tester_email" id="tester_email" size="30"'.$this->getValue($this->testerEmail).'/>
</p>
<p>
<input type="checkbox" name="notify" id="notify" value="True"/>
<label for="notify">Notify me when My Awesome App launches!</label>
</p>
<p>
'.$this->errorLabel().'
<input type="hidden" name="my-form-data" value="process"/>
<input type="hidden" name="notify" value="True"/>
<input type="submit" id="submit" name="Submit" value="Submit"/>
</p>
</form>
</div>';
return $form;
}
}
Sorry for the HTML/PHP gobbledigook, I can see why PHP templating frameworks are so popular ;]
But anyway – we call a function here at the start to check if this is a form submission or not (we’ll write a placeholder for this in a minute). Then we just return the HTML to display for the form.
Most of this is pretty straightforward and just creating a form with HTML. You’ll notice that we have some placeholder code in there to add some extra HTML if the user doesn’t fill out a required field, populate a field with a previous value if there was an error signing up, and actually display the error if there was one at the bottom.
Next add the missing placeholder functions to your class:
function checkInput() {
// Bail right away if our hidden form value isn't there
if (!(isset($_POST['my-form-data']))) { return false; }
// Rest is coming soon!
return true;
}
function required($error) {
if ($error) {
return '<span class="required"> *</span>';
}
}
function getValue($var) {
if (empty($var)) {
return ' value=""';
} else {
return ' value="'.esc_html($var).'"';
}
}
function errorLabel() {
if ($this->testerNameError || $this->testerEmailError || $this->rpgTypeError) {
return '<span class="required">* = Required</span>';
}
}
In the check input function, we just check if the hidden my-form-data field is contained in the POST data, and bail otherwise.
The others are just simple helper functions to print out errors and previous values if they exist.
So – save your plugin and reload the page, and if all works well you should have a beta signup form – that just doesn’t do anything yet!