I would like to combine two fields in a MYSQL database into one for output in JSON using PHP. The query draws from two tables:
The first table looks like
comments
id|userid|comment
1|1|Agree
1|2|Disagree
The second table of users looks like:
users
id|username
1|Bob
2|Joe
Here is my current code (stripped down):
$sql = "SELECT u.id,u.username,c.comment FROM comments `c` ";
$sql.= "LEFT JOIN users `u` ON c.userid = u.id
$res = mysql_query($sql) or die(mysql_error());
//Note there is protection against sql injection and the actual parameterized query is way more complicated: I am simplifying here
while($row = mysql_fetch_assoc($res)) {
$comments[] = $row;
}
echo json_encode(array('comments'=>$comments));
It returns JSON that looks like:
"comments":[{"id":"1","username":"Joe","comment":"Agree"},{"id":"2","username":"Bob","comment":"Disagree"}]
I would like to create combine the id and name of the user into one field to get something like:
"comments: [{"user": "1,Joe","comment":"Agree"},{"user":"2,Bob","comment":"Disagree"}]
Can I use concat? Would appreciate any suggestions on how to do this.