SHARE
TWEET

WordPress insert into database by Samuel Elh

elhardoum Jul 15th, 2015 (edited) 1,295 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. function elh_insert_into_db() {
  3.  
  4.         global $wpdb;
  5.         // creates my_table in database if not exists
  6.         $table = $wpdb->prefix . "my_table";
  7.         $charset_collate = $wpdb->get_charset_collate();
  8.         $sql = "CREATE TABLE IF NOT EXISTS $table (
  9.                 `id` mediumint(9) NOT NULL AUTO_INCREMENT,
  10.                 `name` text NOT NULL,
  11.         UNIQUE (`id`)
  12.         ) $charset_collate;";
  13.         require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
  14.         dbDelta( $sql );
  15.         // starts output buffering
  16.         ob_start();
  17.         ?>
  18.         <form action="/" method="post" id="v_form">
  19.                 <label for="v_name">Hello there! What is your name?</label>
  20.                 <br />
  21.                 <input type="text" name="visitor_name" id="v_name" />
  22.                 <input type="submit" name="submit_form" value="submit" />
  23.         </form>
  24.         <?php
  25.         // does the inserting, in case the form is filled and submitted
  26.         if($_POST["submit_form"] != '' && $_POST["visitor_name"] != '') {
  27.                 $table = $wpdb->prefix."my_table";
  28.                 $name = strip_tags($_POST["visitor_name"], "");
  29.                 $wpdb->insert(
  30.                         $table,
  31.                         array(
  32.                                 'name' => $name
  33.                         )
  34.                 );
  35.         }
  36.         // echoes a success message to the visitor
  37.         if($_POST["submit_form"] != '' && $_POST["visitor_name"] != '') {
  38.                 $name = strip_tags($_POST["visitor_name"], "");
  39.                 echo "<p> Your name <strong>".$name."</strong> was successfully inserted into our database. Thanks!!</p>";
  40.         }
  41.         // outputs everything
  42.         return ob_get_clean();
  43.  
  44. }
  45. // adds a shortcode you can use: [insert-into-db]
  46. add_shortcode('insert-into-db', 'elh_insert_into_db');
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top