Im looking over inherited code with the following (partial) class:
class Model_UserGenre extends Zend_Db_Table_Abstract {...
$select = $this->select()->from(array('ug' => $this->_name), array('user_id'))
->where('genre_id IN (?)', $genreID)
->orwhere('sub_genre_id IN(?)', $genreID)
->group(array('ug.user_id'));
$result = $this->fetchAll($select);
return $result;
...}
This is just a sample code. I am unfamiliar with Zend and have tried to read up on the zend db methods cursorily but to me it seems unnecessarily complicated vs just putting in the query string when I am not using a fully dynamic query
Does zend, especially in this case, present some kind of dynamic capability or efficiency that a direct mysqli or PDO query does not?
Thanks and sorry for the noobish question.
The query builder is just there as a usability layer on top of a PDO. It provides some convenient functionality a PDO does not, like dealing with IN statements. It is also there to implement the adapter design pattern, where your database driver can be very easily swapped out.
Essentially, A PDO will still require you to write raw SQL whereas the query builder will do that for you. Any SQL generated by the query builder will be valid for any SQL adapter the query builder supports (eg. PostgreSQL, MySQL, SQLite).
Related
Can someone provide me a couple clear (fact supported) reasons to use/learn DQL vs. SQL when needing a custom query while working with Doctrine Classes?
I find that if I cannot use an ORM's built-in relational functionality to achieve something I usually write a custom method in the extended Doctrine or DoctrineTable class. In this method write the needed it in straight SQL (using PDO with proper prepared statements/injection protection, etc...). DQL seems like additional language to learn/debug/maintain that doesn't appear provide enough compelling reasons to use under most common situations. DQL does not seem to be much less complex than SQL for that to warrant use--in fact I doubt you could effectively use DQL without already having solid SQL understanding. Most core SQL syntax ports fairly well across the most common DB's you'll use with PHP.
What am I missing/overlooking? I'm sure there is a reason, but I'd like to hear from people who have intentionally used it significantly and what the gain was over trying to work with plain-ole SQL.
I'm not looking for an argument supporting ORMs, just DQL when needing to do something outside the core 'get-by-relationship' type needs, in a traditional LAMP setup (using mysql, postgres, etc...)
To be honest, I learned SQL using Doctrine1.2 :) I wasn't even aware of foreign-keys, cascade operations, complex functions like group_concat and many, many other things. Indexed search is also very nice and handy thing that simply works out-of-the-box.
DQL is much simpler to write and understand the code. For example, this query:
$query = ..... // some query for Categories
->leftJoin("c.Products p")
It will do left join between Categories and Products and you don't have to write ON p.category_id=c.id.
And if in future you change relation from one-2-many to let's say many-2-many, this same query will work without any changes at all. Doctrine will take care for that. If you would do that using SQL, than all the queries would have to be changed to include that intermediary many-2-many table.
I find DQL more readable and handy. If you configure it correctly, it will be easier to join objects and queries will be easier to write.
Your code will be easy to migrate to any RDBMS.
And most important, DQL is object query language for your object model, not for your relational schema.
Using DQL helps you to deal with Objects.
in case inserting into databae , you will insert an Object
$test = new Test();
$test->attr = 'test';
$test->save();
in case of selecting from databae, you will select an array and then you can fill it in your Object
public function getTestParam($testParam)
{
$q=Doctrine_Query::create()
->select('t.test_id , t.attr')
->from('Test t ')
$p = $q->execute();
return $p;
}
you can check the Doctrine Documentation for more details
Zeljko's answer is pretty spot-on.
Most important reason to go with DQL instead of raw SQL (in my book): Doctrine separates entity from the way it is persisted in database, which means that entities should not have to change as underlying storage changes. That, in turn, means that if you ever wish to make changes on the underlying storage (i.e. renaming columns, altering relationships), you don't have to touch your DQL, because in DQL you use entity properties instead (which only happen to be translated behind the scenes to correct SQL, depending on your current mappings).
I am building application which needs to have OOP style MySQL query builder. I want to be able to flexibly build complex queries using only PHP and to get resulting query string for execution with my own database driver.
Does anyone know of a good standalone query builder for PHP? Please note that I don't need database driver I need bare MySQL query builder class (preferably written with camel style function and variable names).
Finally I took Doctrine ORM
and modified it little bit to build SQL instead of DQL.
This works very nice and it able to construct complex queries.
Edit:
You can find my final stable implementation in Stingle framework. Look at Db/QueryBuilder plugin.
DSQL - Query Builder for PHP is exactly what you're looking for, no dependencies and has MIT license:
$query = new atk4\dsql\Query();
$query ->table('employees')
->where('birth_date','1961-05-02')
->field('count(*)')
;
echo "Employees born on May 2, 1961: ".$query->getOne();
https://github.com/atk4/dsql
Documentation: http://dsql.readthedocs.io/
The PhpToolCase library has a stand-alone query builder tool that is quite easy and handy to use.
There is full join support aswell: http://phptoolcase.com/guides/ptc-qb-guide.html
And ya, it seems to be written with camel style function and variable names :)
There is one version of query builder there (LGPL licenced). I haven't used it, but you might want to take a look at it, if it suits your purposes:
http://code.google.com/p/mysql-query-builder/
I was wondering if when using the database library in Codeigniter there was a way to automatically escape all the inputs to prevent injection. I know I can use mysql_real_escape_string() to do it, but I wondered it this was already setup to do this automatically, if not are there any frameworks that have this included?
Thanks!
In order to use prepared statements, you can simply use query bindings with CodeIgniter.
$query = 'SELECT id, name FROM user WHERE name = ?';
$bind = array('Jake');
$this->db->query($query, $bind);
More info found here.
CakePHP runs all model queries through its own methods, if you use the model methods it automatically sanitizes any data passed to the query for you. i.e
$options['conditions'] = array('Product.status'=>$status);
$this->Product->find('first',$options);
Right, pretty much all frameworks that implement any sort of database abstraction/ORM layer will automatically mysql_real_espace your queries. If you don't want to use an entire framework, consider a generic ORM library like Propel or Doctrine. Alternatively, look into prepared statements.
All,
I have a PHP application written in Zend Framework with MVC style. I plan to use Zend_DB to connect to the MySQL database and process queries. I am looking for a wrapper class which makes it easy to use Zend_DB class. This wrapper class will have a constructor that connects to the Mysql db using Zend_DB. It will also have a method to return a singleton instance for each and every db connection made.
Something like:
$pptDB = PPTDB::getInstance();
$pptDB->setFetchMode(PPTDB::FETCH_OBJ);
$result = $pptDB->fetchRow('SELECT * FROM bugs WHERE bug_id = 2');
echo $result->bug_description;
Where class PPTDB extends Zend_DB
Is this something feasible to have? If not, how ls would you use Zend_DB in a major application?
Thanks,
AFAIK it is possible to use Zend_DB as a standalone (well, all classes in that package should also be available of course), but if you're not using the models there is little to gain from is. If you're only interested in the database abstraction I'd recommend PDO, if you want a Zend_DB wrapper Reflection can give you a nice list of properties / functions you can choose to override or not.
http://nl2.php.net/reflection
You should create adapter using Zend_Db::factory() and than use it in Zend_Db_Table_Abstract::setDefaultAdapter(). Then you can get your adapter wherever you want using Zend_Db_Table::getDefaultAdapter() or $table->getAdapter() :)
I am looking for an example of a simple, but functional example of a class extending the mySQLi class in PHP5. I am interested in stored procedures also. Basically what I need is an example of a practical and usable class. I learn best by example and unfortunately I have been unable to find any site or book that seems to have a really solid yet simple example. All the examples I see are way to complicated so I am unable to understand or they are so simple that I might as well just instantiate the class right then and there inline. It would be great if somebody could supply me with an example like this and explain whats going on however well they can. My long term goal is to have a class that I can instantiate that deals with authentication of the database and then takes my SQL statements and supplies the output in variables.
If anyone is willing to take the time to help me out it would be much appreciated!
,Thanks
Did you check PHP PEAR MDB2 ?
http://pear.php.net/package/MDB2
Its not so simple, its the best DAL in php IMHO...
About mysqli, you can take a look at those articles :
ext/mysqli: Part I - Overview and Prepared Statements
Using ext/mysqli: Part II - Extending mysqli
(Quite old, but mysqli extension has not changed that much for a couple of years, so those should still be OK)
You could also have a look at PDO, included in PHP since version 5.1 ; it's an object-oriented API to access multiple DB engines (you don't use mysqli_query, pg_query, oci8_query or stuff like that ; only $pdo->query -- well, your SQL has to be compatible, but that's another problem ;-( )
Another approach would be using an ORM, like, for instance, Doctrine.
It's not a class that extends MySQLi, but a full Framework to abstract the DB engine - with that, you write a schema to describe you DB's structure, and you then use a "pseudo-SQL" language to send queries ; or just (for most cases) the object-oriented API that abstracts SQL.
It's a bit difficult to use, at first, but really powerful and useful (and not bad for productivity, I think, for many kind of projects)
give a try to DALMP: http://code.google.com/p/dalmp/ is support prepared statements and many cache backends
Little bit off topic but why MySQLi? PDO is much better and considered a defacto PHP standard these days. I wrote a simple PDO class a year or two ago, I can give you link if interested.
Here is a simple example of adding built in query timing to the mysqli class.
This assumes you have defined a "MyTimer" class implementing the iTimer interface. iTimer class, in it's simplest form, would record the start and stop times for the specified $key (using microtime() or getrusage() or whatever).
<?php
interface iTimer
{
public function start($key);
public function stop($key);
}
class mysqlp extends mysqli
{
function query($query, $resultmode)
{
$timer = MyTimer::getInstance();
$timer->start('mysqli::query');
$result = parent::query($query, $resultmode);
$timer->stop('mysqli::query');
return $result;
}
}
#usage
$mysqli = new mysqlp("localhost", "my_user", "my_password", "world");
$results = $mysqli->query("SELECT id FROM foo");