I am using MySQL to build a messaging system. Everything works beautifully so far but I need to be able to do one particular thing.
In one of the tables I have the column ‘sender_id’.
I take this ‘sender_id’ and run it through a function which then retrieves the users avatar and outputs the link in the returned JSON response.
I need this link… But I also need to be able to retrieve the ‘sender_id’ itself as a number so that I can test against it in jquery.
So what I ultimately what is for the originaly ‘sender_id’ to be duplicated and put into a kind of virtual column ‘before’ it has been processed by my ‘get avatar’ function.
The code I am using to output the JSON after the queries etc. is as follows:-
/*
* Output
*/
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ( $aRow = mysql_fetch_array( $rResult ) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "version" )
{
/* Special output formatting for 'version' column */
$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
}
if ( $aColumns[$i] == "sender_id" )
{
/* Special output to render Avatar by user id */
$row[] = commentplayer_get_user_avatar($aRow[ $aColumns[$i] ]);
}
else if ( $aColumns[$i] == "message" )
{
/* General output */
$row[] = strip_slashes($aRow[ $aColumns[$i] ]);
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
?>
$aColumns is the array of columns which are defined earlier, obviously ‘sender_id’ is one of these. As you can see I have put in a conditional statement so that the sender_id is retruned as an avatar link rather than the actual sender_id. So to sumarise I just need to be able to pull the actual sender_id out aswell as the avatar, preferably into a separate column.
Any ideas?
You can add a line to the code handling the column
sender_id:This will insert the user id right before the avatar URL in each returned JSON row-array.
In fact, it would be nicer to get rid of the for-loop over the columns, and just fill
$rowwith the items you need, indexed by proper names instead of depending on the order. This makes it easier to see what is actually appended to$output. It does mean that when interpreting the JSON on the client, you will have to treat the row as an object rather than an array.