wpdb LIKE request shows all database data

I would like to get a list of user_nicenames and the ID. But not all the usernames which is what i'm getting now. I understand I should use the % before and after the $name only nothing seems to be working. This is the only way to get some output I found till now;

global $wpdb; //get access to the WordPress database object variable

//get names of all users
$name = $wpdb-esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "SELECT user_nicename, ID
FROM $wpdb-users
WHERE user_nicename LIKE %s
";

$sql = $wpdb-prepare($sql, $name);

$results = $wpdb-get_results($sql);

How do I limit the output to only user_nicenames starting with, so $_POST['name'] .'%' in normal php code.

Topic wp-query wpdb Wordpress sql

Category Web


Can you verify that $_POST['name'] is obtaining a value. I suggest echoing it out to the page for debugging (maybe in comment tags if site is live). If $_POST['name'] is empty, then all results will be returned because the query will say user_nicename LIKE '%'

Just as a precaution in any case, you should do a conditional check to see if $_POST['name'] is set and not empty (if you never want all results returning). If empty or null, then add optional code accordingly, like to display a message that no results were found, etc.. based on how you'd want your application to work.

I suggest breaking up your statement to do the check.. so basically:

$name = '';

if(isset($_POST['name'])){

  $name = stripslashes($_POST['name']);

}

echo '<!-- name: '.$name.' -->';

if($name==null || $name==''){ 

  //TODO: like return;

}else {

  $name = $wpdb->esc_like($name).'%';

  ....
}

Your query is right the like parameter will be

global $wpdb; //get access to the WordPress database object variable

//get names of all users
$name = $wpdb->esc_like(stripslashes($_POST['name']))."%";
$sql = "SELECT user_nicename, ID
FROM $wpdb->users
WHERE user_nicename LIKE %s
";

$sql = $wpdb->prepare($sql, $name);

$results = $wpdb->get_results($sql);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.