in reply to If Problem!!!

Because your SQL statement isn't returning anything. Since it doesn't, then you never enter your while-loop, thus never entering the if-statement.

A few comments:

  1. Don't print your HTML out in your Perl script. At the very least, use CGI's methods for creating HTML. Ideally, you'd use templates (a la HTML::Template, Template Toolkit, or Mason, to name a few).
  2. Your SQL can very possibly break, if $company has naughty characters in it. I would use placeholders, if I were you. Something like:
    my $sql = <<__END_SQL__; SELECT DISTINCT name FROM master WHERE name LIKE ? ORDER BY name __END_SQL__ # stuff here $sth->execute("%${company}%"); # more stuff here
  3. You need to error-check your prepare() call as well as your execute() call. prepare() is where the SQL is checked for syntax. execute() is where it is checked against the database. A number of DBD drivers (such as Oracle) will dump out of prepare() if the tablename is wrong, or the like.

As for your actual problem, I would argue that you haven't through through what you want to do. I would build a list of $ag values within the while-loop. Then, outside the while-loop, I would check to see if you have any $ag values. If you don't, put your "Value not found" select. Otherwise, build the selects.

------
We are the carpenters and bricklayers of the Information Age.

The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.