Web-based applications are becoming increasingly popular due to less demand of client-side resources and easier maintenance than desktop counterparts. On the other hand, larger attack surfaces and developers’ lack of security proficiency or awareness leave Web applications particularly vulnerable to security attacks. One existing approach to preventing security attacks is to compose a redundant system using functionally similar but internally different variants, which will likely respond to the same attack in different ways. However, most diversity-by-design approaches are rarely used in practice due to the implied cost in development and maintenance, significant false alarm rate is also another limitation. In this work, we employ opportunistic diversity inherent to Web applications and their database backends to prevent injection attacks. We first conduct a case study of common vulnerabilities to confirm the effectiveness of opportunistic diversity for preventing potential attacks. We then devise a multi-stage approach to examine database queries, their effect on the database, query results, and user-end results. Next, we combine the results obtained from different stages using a learning-based approach to further improve the detection accuracy. Finally, we evaluate our approach using a real world Web application.