Removing the table names from the column names when using $wpdb->insert()
is what worked for me:
function add_to_affuser($user_id) {
global $wpdb;
$user_info = get_userdata($user_id );
$wpdb->insert( 'mytbl_A', array('name' => $user_info->user_login,
'email' => $user_info->user_email ), array('%s', '%s') );
}
add_action( 'user_register', 'add_to_affuser');
function add_to_aff($user_id) {
global $wpdb;
$user_info = get_userdata($user_id);
$wpdb->insert( 'mytbl_B', array('user_id' => $user_info->ID ), array('%d') );
}
add_action( 'user_register', 'add_to_aff');
While trying to reproduce the issue reported, I noticed that tables created using dbDelta()
(and the database description provided) had lowercase names despite trying to use A
and B
. I was a little unsure of how the prefixes were set up based on your code too.
Here’s a demo plugin that includes the database creation part too. Custom tables are created upon plugin activation. The custom DB tables will be updated when adding a new user.
<?php
/*
Plugin Name: WPSE update custom tables when adding user
Plugin URI: http://wordpress.stackexchange.com/questions/241560
Description:
Version: 0.0.1
Author:
Author URI:
License: GPL2/Creative Commons
*/
/**
* Create the database tables upon activation of this plugin
*
*/
register_activation_hook( __FILE__, 'wpse241560_db_install' );
function wpse241560_db_install() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$sql_affuser = "CREATE TABLE {$wpdb->prefix}affuser (
affiliate_id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
email varchar(512) NULL,
from_date date NULL,
thru_date date NOT NULL,
status varchar(10) DEFAULT 'active' NOT NULL,
type varchar(10) NULL,
PRIMARY KEY (affiliate_id),
KEY status (status)
) $charset_collate;";
$sql_aff = "CREATE TABLE {$wpdb->prefix}aff (
affiliate_id bigint(20) unsigned NOT NULL,
user_id bigint(20) unsigned NOT NULL,
PRIMARY KEY (affiliate_id, user_id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql_affuser );
dbDelta( $sql_aff );
}
/**
* Update affuser table after adding a new user
*/
add_action( 'user_register', 'wpse241560_add_to_affuser');
function wpse241560_add_to_affuser( $user_id ) {
global $wpdb;
$user_info = get_userdata( $user_id );
$wpdb->insert( "{$wpdb->prefix}affuser",
array(
'name' => $user_info->user_login,
'email' => $user_info->user_email
),
array( '%s', '%s' ) );
}
/**
* Update aff table after adding a new user
*/
add_action( 'user_register', 'wpse241560_add_to_aff' );
function wpse241560_add_to_aff( $user_id ) {
global $wpdb;
$user_info = get_userdata( $user_id );
$wpdb->insert( "{$wpdb->prefix}aff",
array(
'user_id' => $user_info->ID
),
array( '%d' ) );
}