Insert data in database using form

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
) );

Leave a Comment