Samuel Elh Blog

WordPress, bbPress, BuddyPress, JavaScript tutorials and snippets

WordPress – How to create a database table and insert data with HTML forms

WordPress tutorial: creating a MySQL database table, and inserting content using the WordPress class wpdb:

In this tutorial, we will learn:

  • How to create a new database table in WordPress
  • How to insert data into this newly created database table

You could use this process to record information about your audience or even use it for a plugin, etc.

First, and with PHP, the following code performs a MySQL query and creates a new database table if it does not exist already, and from this tutorial, the name of the table is my_table which of course you can change to something else:

global $wpdb;
// creates my_table in database if not exists
$table = $wpdb->prefix . "my_table"; 
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table (
	`id` mediumint(9) NOT NULL AUTO_INCREMENT,
	`name` text NOT NULL,
UNIQUE (`id`)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );

Next, we create a simple HTML form containing 2 basic inputs, one for the text to let the viewer type what we request, and another for submitting the form:

<form action="#v_form" method="post" id="v_form">
	<label for="visitor_name"><h3>Hello there! What is your name?</h3></label>
	<input type="text" name="visitor_name" id="visitor_name" />
	<input type="submit" name="submit_form" value="submit" />
</form>

You may have noticed that the action is nothing but a hash, because we don’t work with PHP files here and complicated stuff..

The following step is the last one which detects what the viewer has typed, and inserts it to the database table using $wpdb->insert WordPress class function. If the name was not set (left empty by the viewer), there will be no insert, just a notice for the user to fill out that field :

if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] != "" ) {
	$table = $wpdb->prefix."my_table";
	$name = strip_tags($_POST["visitor_name"], "");
	$wpdb->insert( 
		$table, 
		array( 
			'name' => $name
		)
	);
	$html = "<p>Your name <strong>$name</strong> was successfully recorded. Thanks!!</p>";
}
// if the form is submitted but the name is empty
if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] == "" )
	$html .= "<p>You need to fill the required fields.</p>";

Full code

Now to make this easier to use, we are going to make a quick shortcode to use, so add the following code in your functions.php file, make sure you are working on a WordPress child theme :

function elh_insert_into_db() {

	global $wpdb;
	// creates my_table in database if not exists
	$table = $wpdb->prefix . "my_table"; 
	$charset_collate = $wpdb->get_charset_collate();
	$sql = "CREATE TABLE IF NOT EXISTS $table (
		`id` mediumint(9) NOT NULL AUTO_INCREMENT,
		`name` text NOT NULL,
	UNIQUE (`id`)
	) $charset_collate;";
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
	// starts output buffering
	ob_start();
	?>
	<form action="#v_form" method="post" id="v_form">
		<label for="visitor_name"><h3>Hello there! What is your name?</h3></label>
		<input type="text" name="visitor_name" id="visitor_name" />
		<input type="submit" name="submit_form" value="submit" />
	</form>
	<?php
	$html = ob_get_clean();
	// does the inserting, in case the form is filled and submitted
	if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] != "" ) {
		$table = $wpdb->prefix."my_table";
		$name = strip_tags($_POST["visitor_name"], "");
		$wpdb->insert( 
			$table, 
			array( 
				'name' => $name
			)
		);
		$html = "<p>Your name <strong>$name</strong> was successfully recorded. Thanks!!</p>";
	}
	// if the form is submitted but the name is empty
	if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] == "" )
		$html .= "<p>You need to fill the required fields.</p>";
	// outputs everything
	return $html;
	
}
// adds a shortcode you can use: [insert-into-db]
add_shortcode('elh-db-insert', 'elh_insert_into_db');

WordPress Shortcode

Now that we have added the above snippet of code to our functions file, the shortcode [elh-db-insert] is now ready to be used and you can insert it anywhere around your site, like in a post, page, widget, PHP template..

If the inserting process has worked for you, then play around with it, add other fields, name them, make test inserts, and have fun!

Previews

insert data into database table wordpress tutorial

Digital Ocean

Cheap Cloud SSD Hosting

Get a VPS now starting at $5/m, fast and perfect for WordPress and PHP applications

Sign Up with $10 Credit

11 Comments

  1. Izharul Haque

    May 9, 2016 at 12:49 pm

    It’s very nice tutorial.

  2. Hello this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding skills so I wanted to get
    advice from someone with experience. Any help would
    be enormously appreciated!

    • samuel

      July 11, 2016 at 9:40 am

      Hello,

      This a WordPress powered blog. Sure comes with WYSIWYG (tinymce) editor, and even more. Basically what’s worth a CMS if it does not come with a rich editor?

      The best CMS out there for PHP is WordPress, and for JavaScript try Ghost.

      Good luck.

  3. Thanks, nice tutorial. How about update and delete?

    • there is an failure in the syntax:
      Wrong syntax

      // adds a shortcode you can use: [insert-into-db]
      add_shortcode('elh-db-insert', 'elh_insert_into_db'); <--wrong first parameter 'elh-db-insert'
      Right syntax:// adds a shortcode you can use: [insert-into-db]
      add_shortcode('insert-into-db', 'elh_insert_into_db');
  4. how to connect wordpress with table

  5. i
    like it
    please tell me sir how to get back to frontend

  6. Hi,

    it worked for single value column, but need help in inserting multiple columns.
    Ho to insert multicolumn data in the table?

  7. Thanks a lot working just amazing.

Leave a Reply

Your email address will not be published.

*

© 2017 Samuel Elh - Powered by WordPress, DigitalOcean & NameCheap

Theme by Anders NorenUp ↑

Subscribe to our mailing list

Sign up to receive updates about WordPress, free and premium plugins and themes in general and tips and tricks

* indicates required