This guide shows how to send and save form data to a MySQL database after submission using PHP. A basic understanding of MySQL and PHP is required.
Let’s get started:
- Create your database and table.
The columns in your table will depend on your form’s structure. Check out this guide to see your form’s field names or post keys if you’re not sure what columns to add to your database table.
- For this guide, make sure to add the column “submission_id” in your table.
In this sample contact form, the table looks like the following in phpMyAdmin:
Note: The process for creating or editing your database will depend on your server setup or web host. Reach out to your provider’s support for assistance.
- Now, download and extract this ZIP file containing the code.
- Open the PHP file in your text editor.
- Search for Database Config in the code and replace the values with your database information.
- Next, search for Data to Save and add the POST data to save in your database.
real_escape_string() function to prevent possible SQL injection vulnerabilities. To check your form’s POST data, see How to View Submissions as POST Data.
- Search for Queries to Run and edit the UPDATE query.
Map the post values to your table columns. For more information, see MySQL UPDATE Statement.
- Do the same with the INSERT query.
For more information, see MySQL INSERT Statement.
- Save the PHP file and upload it to your server — take note of the file’s URL.
- Now, set up your form to send data to your PHP file’s URL.
For more information, see Sending Submission Data via a POST Request.
- Send a test entry to your form and confirm the results.