Daniel
Daniel

Reputation: 139

Symfony 2: How to execute sql queries in a service

Last week I started working with Symfony 2 and I am bit confused about how to use models and how to create own specific functions.

I have created a service Testing in the services.yml file:

services:
testing:
class: AppBundle\Service\MyService
 arguments: [ @doctrine.orm.entity_manager ]

This is the class MyService

class myService
{

/**
 * @InjectParams({
 *    "em" = @Inject("doctrine.orm.entity_manager")
 * })
 */


  public function __construct(EntityManager $em)
  {
  $this->em = $em;
  }


  function getQuery($id){
   $sql = "SELECT firstname FROM players WHERE id = $id";

    $em = $this->getDoctrine()->getManager();
    $stmt = $em->getConnection()->prepare($sql);
    $stmt->execute();
    $players = $stmt->fetchAll();
}

I would like to execute a query in the service and load the function getQuery() in the controllor like this:

$locationService = $this->container->get('testing');
$ownFunction = $locationService->getQuery($id);

When I execute the script above I get an error.

Upvotes: 1

Views: 2125

Answers (2)

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10900

Your getQuery method is wrong. Since you have EntityManager injected into constructor you should use it (you don't have getDoctrine method available in your service``)

public function getQuery($id){
    $sql = "SELECT firstname FROM players WHERE id = :id";

    $stmt = $this->em->getConnection()->prepare($sql);
    $stmt->bindValue(':id', $id); //you should do this to be sql-injection safe
    $stmt->execute();

    return $stmt->fetchAll(); //you didn't return anything in your function


}

EDIT: you also miss use Doctrine\ORM\EntityManager; at the top of your class

Upvotes: 2

D3F
D3F

Reputation: 156

I think it has to be

function getQuery($id){
$sql = "SELECT firstname FROM players WHERE id = $id";

$stmt = $this->em->getConnection()->prepare($sql);
$stmt->execute();
$players = $stmt->fetchAll();

"$em = $this->getDoctrine()->getManager();" is not needed anymore because you already injected the Doctrine Entity Manager in your construct as $this->em.

Upvotes: 0

Related Questions