I have saved a bunch of parsed messages in a db, and I want to be able to pull out results depending on user input. I would like to sort by 1-4 values (more options later on), username, id, email or date and time. I’ve been using doctrine to do my other queries, but this one, I just can’t figure out.
My issue is, I don’t see how I could possibly check which values are passed into the method and only query for those.
For example:
User enters “bob” into username and “bob@example.com” into the email field. For this scenario I would need doctrine to look something like this:
$queryBuilder ->select('*') ->from('m2m_messages') ->where('username = ' . $queryBuilder->createNamedParameter($params[username])) ->andWhere('email = ' . $queryBuilder->createNamedParameter($params[email])) $query = $queryBuilder->execute();
But I would like it to change, without creating all the copies separately for each occasion… If I wanted to specify the ID and email, it should only take those values.
I am passing the values in through an array which only contain the search terms I need to use in the sql. For above example it would look something like this:
$params [ username => 'bob', email => 'bob@example.com' ]
I haven’t found a way to implement an if(isset) into my code that would allow me to automatically only use the values I passed into the method.
My goal is to be able to enter details into any number of fields, the values entered get passed in an array, and any combination of them is accepted and crafted into the sql script, without having to write 20+ different sql scripts separately.
Advertisement
Answer
Something like this?
$queryBuilder ->select('*') ->from('m2m_messages'); if (count($params) > 0) { $isFirst = true; foreach ($params as $paramKey => $paramValue) { if ($isFirst) { $queryBuilder->where(sprintf('%1$s = %2$s', $paramKey, $queryBuilder->createNamedParameter($paramValue))); $isFirst = false; } else { $queryBuilder->andWhere(sprintf('%1$s = %2$s', $paramKey, $queryBuilder->createNamedParameter($paramValue))); } } } $query = $queryBuilder->execute();
The concept is to iterate through your parameters and add the where conditions supplied in $params
.