You can't use both redirect and output something else to the browser. If I understand what your code is doing, you probably want to wait with outputting the header and HTML until it's clear the user isn't being redirected.
I see a few more points in your code that could be improved:
- Declare variables for the smallest possible scope where they are needed, for example while( my ($id, $user, .... This will lead to less scoping issues; for example you've declared ($l,$a,$z) twice, which isn't necessary (and you should prefer my over our).
- Avoid the variable names $a or $b as they are special for sort.
- You don't need the foreach my $p (param()) loop since you're accessing the parameters directly by name.
- You don't need the $query = new CGI; since you're not using it anywhere; use either CGI.pm's object-oriented interface or its functional interface.
- You're doing the if($role eq $z) test twice; the second time it'll always be true.
- Instead of scanning the database yourself, look into SQL's WHERE clause and make sure to use placeholders, as documented in DBI.
- If train/main.htm doesn't do any authentication of its own, people will be able to easily circumvent this login form by entering the URL directly.
- See UP-TO-DATE Comparison of CGI Alternatives - personally I'd strongly recommend Mojolicious instead of CGI.pm; see Mojolicious::Guides::Tutorial, it's a very different and IMHO much nicer way to do web development. Update: I just posted an example.