Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Raw SQL with Doctrine

I have some extremely complex queries that I need to use to generate a report in my application. I'm using symfony as my framework and doctrine as my ORM.

My question is this:

What is the best way to pass in highly-complex sql queries directly to Doctrine without converting them to the Doctrine Query Language? I've been reading about the Raw_SQL extension but it appears that you still need to pass the query in sections (like from()). Is there anything for just dumping in a bunch of raw sql commands?

like image 629
Levi Hackwith Avatar asked May 05 '10 16:05

Levi Hackwith


People also ask

Should I use raw SQL?

Conclusion. Raw SQL is for sure the most powerful way to interact with your database as it is the databases native language. The drawback is that you might use features which are specific to that database, which makes a future database switch harder.

Should I use raw SQL or ORM?

ORM is good only for developers and maintenance because most developers aren't very good at SQL, but if you're actually talking about performance, SQL completely trumps it.

Does doctrine prevent SQL injection?

An SQL injection security hole allows an attacker to execute new or modify existing SQL statements to access information that he is not allowed to access. Neither Doctrine DBAL nor ORM can prevent such attacks if you are careless as a developer.


2 Answers

$q = Doctrine_Manager::getInstance()->getCurrentConnection(); $result = $q->execute(" -- RAW SQL HERE -- "); 

See the Doctrine API documentation for different execution methods.

like image 184
Tom Avatar answered Sep 21 '22 06:09

Tom


Yes. You can get a database handle from Doctrine using the following code:

$pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh(); 

and then execute your SQL as follows:

$query = "SELECT * FROM table WHERE param1 = :param1 AND param2 = :param2"; $stmt = $pdo->prepare($query);  $params = array(   "param1"  => "value1",   "param2"  => "value2" ); $stmt->execute($params);  $results = $stmt->fetchAll();   

You can use bound variables as in the above example.

Note that Doctrine won't automatically hydrate your results nicely into record objects etc, so you'll need to deal with the results being returned as an array, consisting of one array per row returned (key-value as column-value).

like image 27
richsage Avatar answered Sep 19 '22 06:09

richsage