Forms pt1

Forms Pt.1

In this blog post I am going to try to show you how to create a form, not just the form itself but also the PHP behind it.

When we are finished a user will be able to enter their name and email and “sign up” using this form. Their name and email will be stored in a database along with several other variables. The code will use HTML, PHP7, and PDO/MYSQL.

This code would be good for having people sign up to a newsletter, email list, sign a petition, etc.

This post assumes that you have a web host and the ability/knowledge to create a database and tables within that database.

The first thing we will need to do is create a database and a table. Name them whatever you want.

We need to give the table seven fields:

  1. id – this is an integer, is the primary key, and will auto increment. This will give each person that signs up a unique number automatically.
  2. name – this is a varchar, length of about 15. This will store the name of the person signing up.
  3. email – this is a varchar, length about 30, and is set to unique. This will store the email of the person signing up and will not allow the
    same email twice.
  4. ip – this is a varchar, length about 20. This will store the ip address of the person signing up.
  5. followup – this is an integer. This will store the number of emails sent to this user.
  6. startdate – this is a timestamp. This will automatically store the date and the time that the user signed up.
  7. subscribe – this is a boolean. This will hold a value that tells if a user has unsubscribed, automatically sets to 0 when a user signs up.

Once you have the table created we can create our “database.php” file and upload it to our site.
This is the code that we will put in database.php – or you can get it here: Database file:

// $config array is used by $db (below) and is where we put the info to access our database.
// You can get the info from the site that hosts your database (usually in the control panel).
// You need to change all of the 'your_value' to your own values.

$config = array(
'host' => 'your_host', //usually localhost
'username' => 'your_username',
'password' => 'your_password',
'dbname' => 'your_database_name',
'charset' => 'utf8'
);

//connect to database
try{
$db = new PDO('mysql:host=' . $config['host'] . ';dbname=' . $config['dbname'] . ';charset=' . $config['charset'], $config['username'], $config['password']);

/*
|setAttribute on $db means that if $db fails to connect to the database it will throw an exception
*/
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}

catch(PDOException $ex) {
echo "An Error Occurred! Please try again later."; //user friendly message
}

You can test this code by uploading it to your site and navigating to it’s url (e.g. http://yoursite.com/database.php). If you see a blank page then it works, else, you will get the error message you set above and you probably need to check those database variables.

Once that is working we need to create the actual page that users will see. You can decorate it however you want but the part that we are going to worry about is the form where users will enter their name and email.

You can get the code here: Form file it’s called “form.php“:

It looks like this (click image):

This is a pretty standard form. The “formhandler1.php” is the file we will work on next and it is the file that does all of the the work once you create it you will put the path to it here. The “size” attribute adjusts the size of the visible data field, you can set this to whatever looks the best in your design. The “maxlength” attribute determines how many characters you can type in to the field and this should be set to match the database.

The “size“, “maxlength“, and “required” attributes have just been added in HTML5 so they are not as widely used as some other ways to validate and control input data, but it is the best way imo and you should start using them along with your current controls. There are many more attributes also, you can get a list here: w3schools

Once the form is on the page we are ready to create the “formhandler1.php” file.

You can get the code here: Form Handler file I will also post it below.

The first thing we will do in the file is add the other file we made called “database.php“.

require 'database.php';

Then we will initialize the variables that we need.

$nameErr = $emailErr = "";
$name = $email = "";
$key = 0;
$ip = $_SERVER['REMOTE_ADDR'];
$day = date("Y/m/d");

$vals = array(
':name'=>$name,
':email'=>$email
);

Now we create a statement to check the name field – that it is not blank, and that it only contains letters and spaces. You can allow numbers and other characters in your version with some adjustments to the preg_match part of this code. I kept it simple because we have the “id” field, so a unique user name is not needed and neither are names with numbers or other special characters.

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//make sure name was input and valid
if (empty($_POST["name"]))
{
$nameErr = "Name is required";
} else
{
$name = test_input($_POST["name"]);
}

if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and spaces please";
}

Now is some code to check the email – that it is not blank and that it is in email format.

//make sure email was input and valid
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
} else
{
$email = test_input($_POST["email"]);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}

We need some code to check if the email we are using to sign up is already in the database.

// make sure email doesn't already exist
//make sure to change tablename to your tablename
$check_email = $db->prepare("SELECT * FROM tablename WHERE email=?");
$check_email->bindValue(1, $email, PDO::PARAM_STR);
$check_email->execute();
$count = $check_email->rowCount();

We need the code that actually enters the data into the database.

// insert new member
//make sure to change tablename to your tablename
$stmt = $db->prepare("INSERT INTO tablename (name, email, ip)
VALUES (:name, :email, :ip)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':ip', $ip);
$stmt->execute();

echo "New records created successfully";

We need the function that the check name and check email parts of the code need to sterilize data.

// function to sterilize input data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

That is all we need! Make sure you put the correct path to your “database.php” file, and make sure you change the 2 “tablename” fields to the name of the table that you created.

The code for the entire “formhandler1.php” file looks like this:

$name,
':email'=>$email
);

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//make sure name was input and valid
if (empty($_POST["name"]))
{
$nameErr = "Name is required";
} else
{
$name = test_input($_POST["name"]);
}

if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and spaces please";
}

//make sure email was input and valid
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
} else
{
$email = test_input($_POST["email"]);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
}

if (empty($nameErr))
{
$key = $key + 1;
} else
{
echo $nameErr;
}

if (empty($emailErr))
{
$key = $key + 1;
} else
{
echo $emailErr;
}

if ($key == 2)
{
// make sure email doesn't already exist
//make sure to change tablename to your tablename
$check_email = $db->prepare("SELECT * FROM tablename WHERE email=?");
$check_email->bindValue(1, $email, PDO::PARAM_STR);
$check_email->execute();
$count = $check_email->rowCount();

if ($count != 0)
{
echo "You are already signed up";
} else
{

try
{

// insert new member
//make sure to change tablename to your tablename
$stmt = $db->prepare("INSERT INTO tablename (name, email, ip)
VALUES (:name, :email, :ip)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':ip', $ip);
$stmt->execute();

echo "New records created successfully";
}

catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}

$db = null;
}
}

// function to sterilize input data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

Now we should have a working form that allows you to enter your name and email and store it in a database!

You have created your main page that contains the form that we created. The “action” part of that form contains the path to the “formhandler1.php” file that we created, and the “formhandler1.php” file contains the path to the “database.php” file that we also created.

It should work!

If you have any problems let me know, I would also be glad to do this all for you for a very reasonable price – just send me a message at ed@32hertz.com


Go back to Main Blog

twittertwitter
twittertwitter