PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 1, 2022

[FIXED] Set parameters in the query based on the condition

 February 01, 2022     doctrine-orm, php, query-builder, symfony     No comments   

Issue

I need to write a query with multiple where condition and OR condition. This OR condition is only when if $location array is not empty. So parameters are needed only when this array is not empty.

I am not sure how to write this parameter condition in this condition.

This is the query I am working on.

$qb = $this->createQueryBuilder("e")
            ->select(
                 "e.vehicleId",
                 "e.schemaId",
                 "e.location",
            )
            ->andWhere("e.vehicleId = :vehicleId")
            ->andWhere("e.optionId = :optionId")
            ->andWhere("e.schemaId = :schemaId");
if (count($position) > 0) {
    $qb->andWhere($qb->expr()->orX(
                $qb->expr()->andX("e.location = :location"),
                $qb->expr()->andX("e.location = :loc")
            ));
}

$qb->setParameters(array(
            "vehicleId" => $vehicleId,
            "schemaId" => $schemaId,
            "location" => $position["location"],
            "loc" => $position["loc"],
        ));

Solution

QueryBuilder has two methods to set the query parameters.

The one you are using (setParameters(array $parameters), and the simpler setParameter($parameterName, $parameterValue).

Use the latter instead of the one you are using, and you can set the parameter where you need it:

if (count($position) > 0) {
    $qb->andWhere($qb->expr()->orX(
                $qb->expr()->andX("e.location = :location"),
                $qb->expr()->andX("e.location = :loc")
            ))
        ->setParameter('location', $position["location"])
        ->setParameter('loc', $position["loc"]);
}


Answered By - yivi
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing