//Place query here, let's say you want all the users that have blue as their favorite color
$sql = "SELECT name FROM user WHERE favorite_color = :color";
//set parameters
//you may set as many parameters as you have on your query
$params['color'] = blue;
//create the prepared statement, by getting the doctrine connection
$stmt = $this->entityManager->getConnection()->prepare($sql);
$stmt->execute($params);
//I used FETCH_COLUMN because I only needed one Column.
return $stmt->fetchAll(PDO::FETCH_COLUMN);
/**
* BC layer for a wide-spread use-case of old DBAL APIs
*
* @deprecated This API is deprecated and will be removed after 2022
*
* @return list<mixed>
*/
public function fetchAll(int $mode = FetchMode::ASSOCIATIVE): array
不再推荐使用 execute和 fetchAll,因为两者都不推荐使用。
* @deprecated Statement::execute() is deprecated, use Statement::executeQuery() or executeStatement() instead
* @deprecated Result::fetchAll is deprecated, and will be removed after 2022
public function getSqlResult(EntityManagerInterface $em)
{
$sql = "
SELECT firstName,
lastName
FROM app_user
";
$stmt = $em->getConnection()->prepare($sql);
$result = $stmt->executeQuery()->fetchAllAssociative();
return $result;
}
And with parameters:
public function getSqlResult(EntityManagerInterface $em)
{
$sql = "
SELECT firstName,
lastName,
age
FROM app_user
where age >= :age
";
$stmt = $em->getConnection()->prepare($sql);
$stmt->bindParam('age', 18);
$result = $stmt->executeQuery()->fetchAllAssociative();
return $result;
}