Yadav Chetan
Yadav Chetan

Reputation: 1894

Fetch string of all id from database using query

Hello i Have tableuser, with column id and many more. now i want all id in string form concatenated with comma separation and appending prefix as A.

means suppose i have records with id 1, 2, 3, 4 etc

now i want result like A1,A2,A3 like this

i did it with my way but its too complex i want to do it with single query. my code are as under its working fine.

$send_idstring='';
        $qry="SELECT concat('A',id) as id FROM `admin` WHERE concat(fname,' ',lname) LIKE '%".addContent($searchVal)."%' ";
        $send_id=mysql_query($qry);
        while($row=mysql_fetch_assoc($send_id)){

            $send_idstring.=$row['id'].',';

        }
        $send_idstring=trim($send_idstring, ",");
        echo $send_idstring; 

it gives me output as i want but i want another way to do it please suggest.

Upvotes: 1

Views: 116

Answers (1)

str
str

Reputation: 44979

Try

SELECT GROUP_CONCAT(CONCAT('A', `id`) SEPARATOR ',') AS idList FROM `admin`;

http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat

Upvotes: 4

Related Questions