0

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.

0

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);
  • And what about sql injection? I read using this will make it vulnerable. – Theetje Dec 8 '17 at 17:05
  • It's the same as my code, apart from dubble vs. single quotes. Result is the same. – Theetje Dec 8 '17 at 17:31
0

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 Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.