Custom query to read user field value

Cyb3r

Well-known member
Hi, can anyone please tell me if this queries is correct:

PHP:
// Check if the field is not set
$value = $db->query("
    SELECT `field_value`
    FROM `xf_user_field_value`
    WHERE `field_id` = 'MyField'
    AND `user_id` = '$userId'
");

// If the field is empty
if(!$value)
{
    // Insert the MyValue into the field
    $db->query("
        UPDATE `xf_user_field_value`
        SET `field_value` = 'MyValue'
        WHERE `field_id` = 'MyField'
        AND `user_id` = '$userId'
    ");
}

For some reason it's not working, however I don't get any error's but still not inserting anything in the field.

Any help will be much appreciated. :)
 
Last edited:
The value for "field_id" needs to be provided as hexadecimal key, not as string.

I don't think so, check here: https://xenforo.com/community/threa...to-personal-details-in-ucp.44008/#post-473145

And here: https://xenforo.com/community/threa...r_field_value-after-import.93961/#post-905931

Both were using exact field_id name, however I figured that if the field is already set I can change it but can't insert new value if it's empty, the UPDATE query is wrong I guess? so what to use? -_-
 
Got it.

PHP:
$db->query("
    INSERT INTO xf_user_field_value (user_id, field_id, field_value)
        SELECT '$userId', 'MyField', '$value'
        FROM xf_user
    ON DUPLICATE KEY UPDATE
        field_value = VALUES(field_value);
");
 
Last edited:
You should be using bound params, not sticking them straight into the query. It's giving me a headache just looking at it...

Liam
 
You should be using bound params, not sticking them straight into the query. It's giving me a headache just looking at it...

Liam

Lol that was only for testing purpose, you should see my full test file you will freak out. :ROFLMAO:

I'm not a pro though but i'm progressing. ;)
 
Back
Top Bottom