Save HTML Form Into Database With PHP MySQL – Simple Example

Welcome to a beginner’s tutorial on how to save an HTML form into the database with PHP and MySQL. So you have finally come to fight the boss stage of full-stack programming – Combining HTML, PHP, and MySQL to save a submitted form into the database.

Saving an HTML form into the database is a simple 3-step process.

  1. Create a database table with the fields you want to capture.
  2. Create the corresponding HTML form, that submits to a PHP script.
  3. In the PHP script, open a database connection and insert the submitted fields.

Yep, it’s really that simple but read on for an actual example!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Saving Forms Useful Bits & Links
The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

  • Create a test database and import 1-dummy.sql.
  • Change the database settings in 3-save.php to your own.
  • Launch 2-form.php in your browser.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SAVING FORMS INTO DATABASE

All right, let us now get started on an example of saving an HTML form into the database.

 

1) CREATE DATABASE TABLE

1a-dummy.sql
CREATE TABLE `survey` (
  `email` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `color` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
ALTER TABLE `survey`
  ADD PRIMARY KEY (`email`);

For this example, we will be doing a simple “survey” on the favorite color that the users like; We will be capturing 3 fields – The email, name, and the color itself.

 

 

2) HTML FORM

2-form.html
<?php
// (A) SAVE SURVEY FORM ON SUBMIT
if (isset($_POST['email'])) {
  require "3-save.php";
}
?>
 
<!-- (B) SURVEY FORM -->
<form method="post">
  <label for="email">Email</label>
  <input type="email" name="email" required/>
  <label for="name">Name</label>
  <input type="text" name="name" required/>
  <label for="color">Favorite Color</label>
  <input type="text" name="color" required/>
  <input type="submit" value="Go!"/>
</form>

Shouldn’t have any trouble with this one too. This is an HTML form with exactly what we want to capture – The email, name, and favorite color. Take note of that if (isset($_POST['email'])) though, we will only include the “save to database” PHP script only when the form is submitted.

 

3) PHP PROCESSING

3-save.php
<?php
// (A) DATABASE CREDENTIALS - CHANGE TO YOUR OWN!
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
 
// (B) CONNECT TO DATABASE
$error = NULL;
try {
  $pdo = new PDO(
    "mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET . ";dbname=" . DB_NAME,
    DB_USER, DB_PASSWORD, [ 
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
  );
} catch (Exception $ex) { $error = $ex->getMessage(); 
 
// (C) INSERT
if (is_null($error)) {
  try {
    $stmt = $pdo->prepare("INSERT INTO `survey` (`email`, `name`, `color`) VALUES (?, ?, ?)");
    $stmt->execute([$_POST['email'], $_POST['name'], $_POST['color']]);
  } catch (Exception $ex) { $error = $ex->getMessage(); }
}

// (D) RESULTS
echo is_null($error) ? "OK" : $error ;

I don’t think this one needs a lot of explanation either – Connect to the database and do an SQL INSERT. That’s all, really.

 

 

EXTRA) SEND EMAIL

Need to send out an email? Just add a few more lines after the database insert is done.

3-save.php
<?php
// (X) SEND EMAIL
if (is_null($error)) {
  $message = "";
  foreach ($_POST as $k=>$v) { $message .= "$k : $v\r\n"; }
  if (!mail("admin@site.com", "Survey Received", $message)) {
    $error = "Failed to send email";
  }
}

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

Save HTML Form Into Database (Click to enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *