Symfony2 example of using doctrine to summarize _php of database Query method

Source: Internet
Author: User
Tags sql injection try catch

This article is an example of how Symfony2 uses doctrine to query database queries. Share to everyone for your reference, specific as follows:

Variables used in the predefined text:

$em = $this->getdoctrine ()->getentitymanager ();
$repository = $em->getrepository (' acmestorebundle:product ')

1. Basic methods

$repository->find ($id);
$repository->findall ();
$repository->findonebyname (' Foo ');
$repository->findallorderedbyname ();
$repository->findoneby (Array (' name ' => ' foo ', ' Price ' => 19.99));
$repository->findby (Array (' name ' => ' foo '), Array (' Price ' => ' ASC '));

2, DQL

$query = $em->createquery (
' SELECT p acmestorebundle:product p WHERE p.price >:p Rice ORDER by P.price ASC '
)->setparameter (' Price ', ' 19.99′ ');
$products = $query->getresult ();

Note:

(1) A result can be obtained by:

$product = $query->getsingleresult ();

Using the Getsingleresult () method you need to wrap it in a try catch statement to ensure that only one result is returned, as in the following example:

->setmaxresults (1);
try {
$product = $query->getsingleresult ();
} catch (\doctrine\orm\noresultexception $e) {
$product = null;
}

(2) Setparameter (' Price ', ' 19.99′ '); Use this external method to set the value of the "placeholder" price in the query, rather than writing the value directly into the query statement to help prevent SQL injection attacks, you can also set multiple parameters:

->setparameters (Array (
' price ' => ' 19.99′,
' name ' => ' Foo '
))

3, the use of doctrine query generator

$query = $repository->createquerybuilder (' P ')
->where (' p.price >:p rice ')
->setparameter (' Price ', ' 19.99′ '
->orderby (' P.price ', ' ASC ')
->getquery ();
$products = $query->getresult ();

I hope this article will help you with the PHP program design based on Symfony framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.