So I have this code that checks 4 parameters (author, title, keyword and subject) to do some dynamic sql query generation for a project I’m working on and I was just wondering if anyone knew of a better way to write this out. I get the feeling this is a really inefficient way to do this but it’s late and I’m tired. Please let me know if you know of any better way to do this, it’s just a bunch of if/else case checking statements at this point.
Thanks!
if(_author!=null)
{
query += authorQ;
if(_title != null)
{
if(conjunct[0] == 0)
{
query += " AND ";
query += titleQ;
}
else
{
query += " OR ";
query += titleQ;
}
if(_keyword != null)
{
if(conjunct[1] == 0)
{
query += " AND ";
query += keywordQ;
}
else
{
query += " OR ";
query += keywordQ;
}
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
else
{
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
}//title = null
else
{
if(_keyword != null)
{
if(conjunct[1] == 0)
{
query += " AND ";
query += keywordQ;
}
else
{
query += " OR ";
query += keywordQ;
}
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
else //keyword null
{
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
//if subject's null at this point we don't care
}
}
}
else //author null
{
if(_title != null)
{
if(conjunct[0] == 0)
{
query += " AND ";
query += titleQ;
}
else
{
query += " OR ";
query += titleQ;
}
if(_keyword != null)
{
if(conjunct[1] == 0)
{
query += " AND ";
query += keywordQ;
}
else
{
query += " OR ";
query += keywordQ;
}
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
else
{
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
}//title = null
else
{
if(_keyword != null)
{
if(conjunct[1] == 0)
{
query += " AND ";
query += keywordQ;
}
else
{
query += " OR ";
query += keywordQ;
}
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
else //keyword null
{
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
//if subject's null at this point we don't care
}
}
}
How about a more structured and scalable approach, see example below. By the way, you shouldn’t really be putting user input straight into SQL queries – use prepared statements instead to try to guard against injection attacks.