WordPress Selecting a variable


In the most basic form, it is possible to select a single variable from a table by calling the object's get_var method passing in an SQL query.

global $wpdb;
$user = $wpdb->get_var( "SELECT ID FROM $wpdb->users WHERE user_email='foo@bar.com'" );

It is very important to note that any untrusted values used in queries must be escaped in order to protect against attacks. This can be done using the object's prepare method.

global $wpdb;
$email = $_POST['email'];
$user = $wpdb->get_var(
    $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE user_email=%s", $email )
if( !is_null( $user ){
    echo $user; 
} else {
    echo 'User not found';