-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
4

1 回答 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.
于 2013-03-30T08:12:51.547 回答