Asterisk Phone to IP dynamic routing.?

Hello I am new to Asterisk.

I want to setup Asterisk for Phone to IP calls, but not using static routing which could be done easily in extensions.conf. I want dynamic mapping

I had a digium E1 card. All i want is when a user dials my E1, I get the CLI of this user and query some database (mysql e.g) and get a SIP address of another user or multiple user. And finally send an Invite to this SIP address. Can any one tell me where should i start, i mean in which files I have to modify the code. And what is the best way to do this.

Thanking you all in advance.

You could call an agi script that sets a variable in your dialplan. Something like:

In extensions.conf:
exten => s,1,AGI(findnum.agi|${ARG1})
exten => s,2,Dial(SIP/${myexten},15)
exten => s,3,Hangup

Agi script could look something like:

use DBI;
$dbh = DBI->connect ("dbi:Pg:dbname=mydb;host=;port=5432", "uname", "pass");
if ( !defined $dbh ) {
        print "SET VARIABLE myexten 0"; 
if ( !defined $ARGV[0] ) {
        print "SET VARIABLE myexten 0";
$query = "SELECT extension FROM extensions WHERE ext=$ARGV[0]";
$sth = $dbh->prepare($query);
        if ($sth->rows != 0) {
                $result = $sth->fetchrow_hashref();
                if ($result->{forward_flag} == "f") {
                        print "SET VARIABLE myexten 0"; 
                print "SET VARIABLE myexten $result->{this_exten}";
                 print "SET VARIABLE myexten 0";

Thanx for your response and the code sample. :smile:
Helped me a lot. At least it gave a clear direction where to go and what to do. But since im a C programmer I’ll to try to convert this thing into C. and if I coudn’t I’ll let you know ( or most probably use this as such ). Thanking you once again.