maya
maya

Reputation: 21

sql query working in phpmyadmin - not working within php

I have a function in a WordPress plugin I am about to write (my first one) that should check if a given ID belongs to a user with a certain role ('dance_couple' in this case).

$sc_user_id is the id passed in the shortened code.

function user_is_dance_couple($sc_user_id){
   global $wpdb;
   $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->usermeta WHERE user_id = %d AND meta_value LIKE `%dance_couple%`", $sc_user_id));
   if($count == 1){ return true; } else { return false; }
}

if (user_is_dance_couple(1)) {
  // here comes what should be done if the user has the right role
}

Question: The weird thing is, that I copied a simpler version of the function (https://wordpress.stackexchange.com/questions/165691/how-to-check-if-a-user-exists-by-a-given-id) and adapted it. so the only thing I changed is the bit of sql code (that works fine in sql), the function as it was before also works fine - I have no idea what I did wrong.

I already tried:

  1. changing the single quotes to the thing between the double quotes " ` "
  2. taking the sting out and adding it in a variable
  3. adding the table names in before the columns

Thanks for the help!

Upvotes: 1

Views: 255

Answers (2)

Marcello Perri
Marcello Perri

Reputation: 610

I don't think you can use the GLOBAL object $wpdb inside a query and inside the quotation. What I would do is create another variable and put the value of $wpdb->usermeta in that variable.

in this way:

$user = $wpdb->usermeta;
global $wpdb;
$query = "SELECT COUNT(*) FROM %d WHERE user_id = %d AND meta_value LIKE `%dance_couple%`";
$count = $wpdb->get_var($wpdb->prepare($query, $user, $sc_user_id));

Or the long version:

$count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM %d WHERE user_id = %d AND meta_value LIKE `%dance_couple%`", $user, $sc_user_id));

The syntax of the query looks correct, try in this way

Upvotes: 0

RRikesh
RRikesh

Reputation: 14381

No need for SQL queries. You could do something like that:

$user_id = 1; # or whatever user you need
$role_to_find = 'dance_couple';

$user = get_userdata( $user_id );

if( false !== $user ){
    # User found, do your stuff
    $user_roles = $user->roles;
    # var_dump( $user_roles );

    if( in_array( $role_to_find, $user_roles ) ){
        echo 'User has the role';
    }else {
        echo 'User does not have the role';
    }
}else{
    echo 'User not found';
}

Upvotes: 1

Related Questions