Skip to content
Advertisement

WordPress get_var query

I have created some custom tables within the WP database, and I’m referencing a table called ‘projects’ in this instance with this query.

‘pr_no’ is the Project Number

<?php
$current_user = wp_get_current_user();
$projectref = $wpdb->get_var("SELECT pr_no FROM $wpdb->projects WHERE ID=$current_user->ID");
echo "{$projectref}";

However, it echos nothing, and comes up blank. Where have I gone wrong?

At first I thought it was because I’d created my own table within WP, but apparently that’s allowed. So I’m stuck!

–Update–

Fixed it for anyone who’s interested, you don’t need the $wdbp prefix on custom tables in a query. Amending the code to below fixes it.

<?php
$current_user = wp_get_current_user();
$projectref = $wpdb->get_var(“SELECT pr_no FROM projects WHERE ID=$current_user->ID”);
echo “{$projectref}”;

Advertisement

Answer

Fixed it for anyone who’s interested, you don’t need the $wdbp prefix on custom tables in a query. Amending the code to below fixes it.

<?php

    $current_user = wp_get_current_user();
    $projectref = $wpdb->get_var(“SELECT pr_no FROM projects WHERE ID=$current_user->ID”);
    echo “{$projectref}”;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement