0

I have following foreach loop code...

<?php

$usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" );

foreach ( $usernames as $username ) 
{
    echo $username->user_name;
}

?>

When I use echo $username->user_name; it displays all the usernames from the user_name column of database. I want to display only the first username from the list. How to do... Pl help... Thanks...

  • using it inside foreach will obviously print all usernames – Atlas_Gondal Jul 14 '18 at 8:01
  • @Atlas_Gondal... Then plz tell me how to do.. Thanks – Minesh Jul 14 '18 at 8:04
  • how you want to display them? like in list item or row by row etc – Atlas_Gondal Jul 14 '18 at 8:11
  • Actually I want to display in add / remove dynamic input fields... – Minesh Jul 14 '18 at 8:15
  • can you share the html snippet for displaying them in inside input fields? – Atlas_Gondal Jul 14 '18 at 8:16
1
$usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698 LIMIT 1" 
  • Andrea Somovigo... Actually I want to display all usernames individually... Since echo $username->user_name; displays all usernames in one row... – Minesh Jul 14 '18 at 8:09
1

It's a little bit hard to guess, what exactly are you trying to achieve, but... Based on your answer, here's much cleaner and more secure code, you can use:

global $wpdb;
$usernames = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT user_name FROM {$wpdb->prefix}project_members WHERE project_id = %d",
        698
    )
);

if ( ! empty($usernames) ) {
    echo $usernames[0]->user_name;
} else {
    // there are no users
}
-1

I have found the solution... Here it is...

<?php

$usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" );

foreach ( $usernames as $username ) 
{
    $member_username[] = $username->user_name;
}

echo $member_username[0];

?>

Hope it may help other users.

  • 3
    No, no, no... You don't need another array just to access first item... And where's the escaping? And what if there are no users? Your code will cause errors in such case... – Krzysiek Dróżdż Jul 14 '18 at 9:41

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.