-1

I have a PHP function that returns me the specific set of userids in an array. I want to create a function that will convert these userids into usernames. I know how I can create a query to convert each one and then run the query in a loop. But is there a better way that I can do it for the whole array. Like a single query that would accept multiple values or something. My Array is as simple as:

[0] => 126312
[1] => 128383
[2] => 987376
[3] => 563542
2
  • for insert, you can insert multiple records like: INSERT INTO TableName VALUES ('$id1'), ('$id2'), ('$id3'), ...
    – user1646111
    Mar 30, 2013 at 8:07
  • Not insert, I already have the Userid, I want the usernames for them.
    – Aayush
    Mar 30, 2013 at 8:08

1 Answer 1

2

Assuming a table called "user" and fields "id" and "username", you could do: (see http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in )

$ids = array( [0] => 126312
[1] => 128383
[2] => 987376
[3] => 563542);

// do pre logic, e.g connecting...

// sanitize input:
$ids = array_map( "intval", $ids );

$sql = "SELECT user.username FROM user WHERE user.id IN(". implode( ",", $ids ) .")";

// do fetch logic.
1
  • Thanks! I'm still learning SQL. The IN statement works like the in_array() of PHP. Nice!
    – Aayush
    Mar 30, 2013 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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