MySQL: CDR accountcode is from wrong sipfriends entry

I have Asterisk setup as a simple media gateway to our hosted PBX platform (pbxnsip). Everything works perfectly except Asterisk is grabbing the accountcode value from the last entry added to the MySQL sipfriends table and not from the correct entry when making a call from a VoIP phone to the PSTN (through its PRI card). Keep in mind the VoIP phone is registered to pbxnsip and not Asterisk. What makes this even more puzzling is that Asterisk clearly knows who the correct customer is by the value that it is putting in the CDR channel field. I must have something wrong in the sipfriends table but I can’t figure out what it is since all calls process normally. I think was is making this work like this is that the pbxnsip server has one IP address but 30 domains i.e.,,, etc.

I have th following fields set in sipfriends (with examples), which I would think would be the only ones that matter:

name =
host =
outboundproxy =
ipaddr = (IP address of pbxnsip)
accountcode = 12345 (account code of the company’s service)

I simply have this repeated for each hosted PBX customer. All inbound and outbound call routing seems to work without issue.

Here is a SIP INVITE from pbxnsip on its way to Asterisk that is not getting the correct accountcode:

YYY.YYY.YYY.YYY = IP address of Asterisk
5555555555 = VoIP phone's caller ID (originator of the call)
4444444444 = Number being called on the PSTN

INVITE sip:4444444444@YYY.YYY.YYY.YYY;user=phone SIP/2.0.
Via: SIP/2.0/UDP XXX.XXX.XXX.XXX:5060;branch=z9hG4bK-01f02e73e8f438d903937c749ce856a5;rport.
From: "Michael Shuler" <;user=phone>;tag=329602843.
To: <sip:4444444444@YYY.YYY.YYY.YYY;user=phone>.
Call-ID: c5ae25d4@pbx.
CSeq: 21045 INVITE.
Max-Forwards: 70.
Contact: <sip:5555555555@XXX.XXX.XXX.XXX:5060;transport=udp>.
Supported: 100rel, replaces, norefersub.
Allow-Events: refer.
Accept: application/sdp.
User-Agent: pbxnsip/
P-Asserted-Identity: "Michael Shuler" <;user=phone>.
Content-Type: application/sdp.
Content-Length: 204.
o=- 218340900 218340900 IN IP4 XXX.XXX.XXX.XXX.
t=0 0.
m=audio 59798 RTP/AVP 0 101.
a=rtpmap:0 pcmu/8000.
a=rtpmap:101 telephone-event/8000.
a=fmtp:101 0-16.

In the from field it states the domain of the sipfriends entry that it should use for the account code. But for some reason it always grabs the last one in the MySQL table instead. But again the channel entry in the CDR table will be SIP/ so Asterisk is clearly able to see the domain. This makes me believe that this is a bug of some form but I’m sure someone else would have discovered it by now.

I am running Asterisk 1.4.24 and Addons 1.4.7. I was on 1.4.22 and just upgraded to 1.4.24 which did not fix it. Any help would be greatly appreciated.