Cody Tetreault Cody Tetreault - 1 month ago 16
MySQL Question

Wordpress: Using get_current_user_id() result into my DB table with an HTML form

I have a plugin that contains an HTML form which sends POST data to a DB table.
It works perfectly fine excluding one thing. The logged in user's ID is not being sent to the DB table. I think it might be my IF statement just before step #2 here. I've changed it around so many times but haven't had any results. What I DO know is that this if statement works with a GET request, and It actually does give you the user's ID, but apparently not with a POST request.

function ml_install() {
// #1 CREATE TABLE
global $wpdb;
// creates ml_char in database if not exists
$table = $wpdb->prefix . "ml_char";
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table (
`wp_id` mediumint(9) NOT NULL,
`char_id` mediumint(9) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
UNIQUE (`char_id`)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
// starts output buffering
ob_start();
if ( is_user_logged_in() ) {
$wpid = get_current_id();
}
// #2 CREATE HTML FORM
?>
<form action="#ml_form" method="post" id="ml_form">
<input type="hidden" name="wp_id" value="<? echo $wpid; ?>"/>
<input type="text" name="character_name" id="character_name" />
<input type="submit" name="submit_form" value="submit" />
</form>
<?php
$html = ob_get_clean();
// #4 INSERT FORM DATA INTO DB
if ( isset( $_POST["submit_form"] ) && $_POST["character_name"] && $_POST["wp_id"] != "" ) {
$table = $wpdb->prefix."ml_char";
$name = strip_tags($_POST["character_name"], "");
$wpdb->insert(
$table,
array(
'name' => $name,
'char_id' => $wp_id
)
);
$html = "<p>Greetings <strong>$name</strong>, and welcome to Hyreath.</p>";
}

Answer

Ok people, I figured out what my issue was. I had misspelled a column name in my array. Fellow user Webcitron pointed me in the right direction.

Here is the functional code that allows me to grab someone's current Wordpress ID from the wp_users table in the WPDB and insert that into my own table. So now whenever a user comes to my website and creates new characters, all those characters will belong to that specific user, instead of not belonging to anyone. I really hope this helps someone out.

HTML FORM

plugin code from head to toe

phpmyadmin result set