questions

How to insert current username to database in WP

Rate this post
if(isset($_POST['submit'])){
$tablename = 'student_reg'; 
$data = array(
'user' => [$current_user],
'name' => $_POST['name'],
'age' => $_POST['age'],
'address' => $_POST['address'],
'telnumber' => $_POST['telnumber'],
'exam' => $_POST['exam'],
);
global $wpdb, $current_user;
$current_user = wp_get_current_user();
$current_username = $current_user->user_login;

$wpdb->insert($tablename, $data, $format=NULL);
}

I want to insert current username to database but it doesn’t working. Anyone can help me to solve this problem.

 

✔️Solution:

There is an issue in the order of referencing variables in your code. Try adding $current_user and $current_username to the top of the block and also, remove the square brackets in the line 'user' => [$current_username],

if(isset($_POST['submit'])){
  global $wpdb;
  $current_user = wp_get_current_user();
  $current_username = $current_user->user_login;

  $tablename = 'student_reg'; 
  $data = array(
    'user' => $current_username,
    'name' => $_POST['name'],
    'age' => $_POST['age'],
    'address' => $_POST['address'],
    'telnumber' => $_POST['telnumber'],
    'exam' => $_POST['exam'],
  );

  $wpdb->insert($tablename, $data, $format=NULL);
}

Leave a Reply

Your email address will not be published.

Back to top button