Insert data in database using form

I am writing a simple plugin that create a table with name “newsletter” in database and provide a shortcode to put a registration form in pages.
the form contain “name” and “email”.
i have problem with inserting the form data(name+email) in database.
i wrote this:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
function insertuser(){
global $wpdb;
$table_name = $wpdb->prefix . "newsletter";
$wpdb->insert($table_name, array('name' => $name, 'email' => $email) ); 
}
?> 

but id does not work. what should i do to get data from form and insert into table?

Related posts

Leave a Reply

1 comment

  1. The two variables $name and $email are unknown inside the function. You have to make them globally available inside it by changing global $wpdb into global $wpdb, $name, $email:

    require_once('../../../wp-load.php');
    
    /**
     * After t f's comment about putting global before the variable.
     * Not necessary (http://php.net/manual/en/language.variables.scope.php)
     */
    global $name = $_POST['name'];
    global $email = $_POST['email'];
    
    function insertuser(){
      global $wpdb, $name, $email;
      $table_name = $wpdb->prefix . "newsletter";
      $wpdb->insert($table_name, array('name' => $name, 'email' => $email) ); 
    }
    
    insertuser();
    

    Or, you can put the variables in the function’s arguments:

    require_once('../../../wp-load.php');
    
    $name = $_POST['name'];
    $email = $_POST['email']
    
    function insertuser( $name, $email ) {
      global $wpdb;
    
      $table_name = $wpdb->prefix . 'newsletter';
      $wpdb->insert( $table_name, array(
        'name' => $name,
        'email' => $email
      ) );
    }
    
    insertuser( $name, $email );
    

    Or, without function:

    require_once('../../../wp-load.php');
    
    global $wpdb;
    
    $name = $_POST['name'];
    $email = $_POST['email'];
    $table_name = $wpdb->prefix . "newsletter";
    $wpdb->insert( $table_name, array(
        'name' => $name,
        'email' => $email
    ) );