Call data records (CDR)

I have a databse in mySQl that stores my contacts that includes name and phone numbers basically…!!
now what i want is when any of my contacts calls in there must be an entry to another database table that shows that the number is n identified one
If someone other than in the contacs database calls in then there must be an entry in some another database table depicting that the caller has called from an unidentified number…!!

can any1 suggest me how should i proceed with this??
basically i want to ask how to connect asterisk to the existent mySQL database and check whether the callerID exists in the contacts list or not…??

please help!!
thanks in advance

When ever call is received, call agi script and pass the caller number to agi. In agi you can write code to connect to database and search for the caller number. If caller exists then insert record in Table A else insert record in Table B.