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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x