Query for build at runtime according to program condition
What points should be kept in mind while writing queries as under?
$sql=" And two=2";
$sql.=" And three=3";
$sqlquery="select * 开发者_高级运维from".$sql;
I want to make complex queries like the example
You'd better add where 1=1
into your main query. This way you could or could not have any number of AND-joined conditions.
Like this:
$base_query = 'select * from table where 1=1';
$base_query.= 'and two = 2';
$base_query = 'and three = 3';
UPDATE: Doctrine ORM style quering:
//$em is instance of EntityManager
$qb = $em->createQueryBuilder();
$qb->select('u')
->from('User', 'u')
->where('u.id = ?1')
->orderBy('u.name ASC');
//you could add any part of query later
$qb->andWhere("u.name = 'John'");
$query = $qb->getQuery();
$result = $query->getResult();
I personally preffer to do that with arrays something like that:
$where = array();
$where[] = 'Two = 2'
$where[] = 'Three = 3';
$sql = implode(' AND ', $where);
Other option which i think is better to use some database absraction class / active record
Regards.
精彩评论