One way to do this would be to query the DB for all the students, then set a condition on your submit or elsewhere that if the number of students for a given teacher is 25 then fail the submit and display a dialog instead. You can do this by using rules on a button. First rule would check the condition and display error dialog as needed then stop processing rules. Second rule with do the submit. This method I'm describing would allow you to achieve what you want without any code. The condition you have to write is a little complex (with filtering and count logic) but should be possible using the condition builder UI in InfoPath.
Shiraz Cupala / Microsoft InfoPath MVPQdabra® Software / Streamline data gathering to turn process into knowledge