php - WPDB: how to get the value of a field in a custom database table

admin2025-06-03  3

For my WordPress site, I would like to echo the value of a column in a row (determined by the user's ID) of a table in the database for my site. This table was created by a plugin so it is not accessible through the user meta. I have to try and get the value from the table created by the plugin.

For this example, the value is located in the "plugintable" table in the database and the column is "columnname". How get I get the value based on matching the user's ID with the "ID" row?

I've gotten here from the help of other online sources, but I'm stuck.

<?php
    global $wpdb, $table_prefix;
    $user_ID = get_current_user_id();
    $value = $wpdb->get_var('SELECT columnname FROM '.$table_prefix.'plugintable WHERE ID = '.$user_ID);

    echo $value;
?>

For my WordPress site, I would like to echo the value of a column in a row (determined by the user's ID) of a table in the database for my site. This table was created by a plugin so it is not accessible through the user meta. I have to try and get the value from the table created by the plugin.

For this example, the value is located in the "plugintable" table in the database and the column is "columnname". How get I get the value based on matching the user's ID with the "ID" row?

I've gotten here from the help of other online sources, but I'm stuck.

<?php
    global $wpdb, $table_prefix;
    $user_ID = get_current_user_id();
    $value = $wpdb->get_var('SELECT columnname FROM '.$table_prefix.'plugintable WHERE ID = '.$user_ID);

    echo $value;
?>
Share Improve this question edited Jan 31, 2019 at 22:34 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Jan 31, 2019 at 19:13 StevenSteven 231 silver badge3 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 6

OK, so first of all, you should always use proper escaping, when building the queries.

This is how your code can look after fixing:

global $wpdb;
$value = $wpdb->get_var( $wpdb->prepare(
    " SELECT column_name FROM {$wpdb->prefix}plugin_table WHERE ID = %d ",
    get_current_user_id()
) );

The things you have to take care of:

  1. You have to change column_name to proper column name you want to get.
  2. You have to change plugin_table to proper table name you want to get the value from.
  3. You have to change ID to proper name of column that stores the user id in given table.
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748955975a315136.html

最新回复(0)