<p>At the moment my code (PHP) has too many SQL queries in it. eg...</p>

<pre><code>// not a real example, but you get the idea...
$results = $db-&gt;GetResults("SELECT * FROM sometable WHERE iUser=$userid");
if ($results) {
    // Do something
}
</code></pre>

<p>I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns..</p>

<p>I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?</p>

[{'answer_id': 37795, 'author': 'Matthew Watson', 'author_id': 3839, 'author_profile': 'https://Stackoverflow.com/users/3839', 'pm_score': 2, 'selected': False, 'text': '<p>Use a ORM package, any half decent package will allow you to</p>\n\n<ol>\n<li>Get simple result sets</li>\n<li>Keep your complex SQL close to the data model</li>\n</ol>\n\n<p>If you have very complex SQL, then views are also nice to making it more presentable to different layers of your application.</p>\n'}, {'answer_id': 37801, 'author': 'mattruma', 'author_id': 1768, 'author_profile': 'https://Stackoverflow.com/users/1768', 'pm_score': 2, 'selected': False, 'text': "<p>We were in a similar predicament at one time.  We queried a specific table in a variety of ways, over 50+.  </p>\n\n<p>What we ended up doing was creating a single Fetch stored procedure that includes a parameter value for the WhereClause.  The WhereClause was constructed in a Provider object, we employed the Facade design pattern, where we could <strong>scrub</strong> it for any SQL injection attacks.  </p>\n\n<p>So as far as maintenance goes, it is easy to modify.  SQL Server is also quite the <strong>chum</strong> and caches the execution plans of dynamic queries so the the overall performance is pretty good.  </p>\n\n<p>You'll have to determine the <strong>performance</strong> drawbacks based on your own system and needs, but all and all, this works <strong>very well</strong> for us.</p>\n"}, {'answer_id': 37831, 'author': 'Rik Heywood', 'author_id': 4012, 'author_profile': 'https://Stackoverflow.com/users/4012', 'pm_score': 0, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/22278/whats-a-good-way-to-encapsulate-data-access-with-phpmysql">This other question</a> also has some useful links in it...</p>\n'}, {'answer_id': 38053, 'author': 'Gary Richardson', 'author_id': 2506, 'author_profile': 'https://Stackoverflow.com/users/2506', 'pm_score': 2, 'selected': False, 'text': "<p>First up, you should use placeholders in your query instead of interpolating the variables directly. PDO/MySQLi allow you to write your queries like:</p>\n\n<pre><code>SELECT * FROM sometable WHERE iUser = ?\n</code></pre>\n\n<p>The API will safely substitute the values into the query.</p>\n\n<p>I also prefer to have my queries in the code instead of the database. It's a lot easier to work with an RCS when the queries are with your code. </p>\n\n<p>I have a rule of thumb when working with ORM's: if I'm working with one entity at a time, I'll use the interface. If I'm reporting/working with records in aggregate, I typically write SQL queries to do it. This means there's very few queries in my code.</p>\n"}, {'answer_id': 38186, 'author': 'Slacker', 'author_id': 4053, 'author_profile': 'https://Stackoverflow.com/users/4053', 'pm_score': 1, 'selected': False, 'text': "<p>There are some libraries, such as MDB2 in PEAR that make querying a bit easier and safer.</p>\n\n<p>Unfortunately, they can be a bit wordy to set up, and you sometimes have to pass them the same info twice.  I've used MDB2 in a couple of projects, and I tended to write a thin veneer around it, especially for specifying the types of fields.  I generally make an object that knows about a particular table and its columns, and then a helper function in that fills in field types for me when I call an MDB2 query function.</p>\n\n<p>For instance:</p>\n\n<pre><code>function MakeTableTypes($TableName, $FieldNames)\n{\n    $Types = array();\n\n    foreach ($FieldNames as $FieldName =&gt; $FieldValue)\n    {\n        $Types[] = $this-&gt;Tables[$TableName]['schema'][$FieldName]['type'];\n    }\n\n    return $Types;\n}\n</code></pre>\n\n<p>Obviously this object has a map of table names -> schemas that it knows about, and just extracts the types of the fields you specify, and returns an matching type array suitable for use with an MDB2 query.</p>\n\n<p>MDB2 (and similar libraries) then handle the parameter substitution for you, so for update/insert queries, you just build a hash/map from column name to value, and use the 'autoExecute' functions to build and execute the relevant query.</p>\n\n<p>For example:</p>\n\n<pre><code>function UpdateArticle($Article)\n{\n    $Types = $this-&gt;MakeTableTypes($table_name, $Article);\n\n    $res = $this-&gt;MDB2-&gt;extended-&gt;autoExecute($table_name,\n        $Article,\n        MDB2_AUTOQUERY_UPDATE,\n        'id = '.$this-&gt;MDB2-&gt;quote($Article['id'], 'integer'),\n        $Types);\n}\n</code></pre>\n\n<p>and MDB2 will build the query, escaping everything properly, etc.</p>\n\n<p>I'd recommend measuring performance with MDB2 though, as it pulls in a fair bit of code that might cause you problems if you're not running a PHP accelerator.</p>\n\n<p>As I say, the setup overhead seems daunting at first, but once it's done the queries can be simpler/more symbolic to write and (especially) modify. I think MDB2 should know a bit more about your schema, which would simpify some of the commonly used API calls, but you can reduce the annoyance of this by encapsulating the schema yourself, as I mentioned above, and providing simple accessor functions that generate the arrays MDB2 needs to perform these queries.</p>\n\n<p>Of course you can just do flat SQL queries as a string using the query() function if you want, so you're not forced to switch over to the full 'MDB2 way' - you can try it out piecemeal, and see if you hate it or not.</p>\n"}, {'answer_id': 87738, 'author': 'Willem', 'author_id': 15447, 'author_profile': 'https://Stackoverflow.com/users/15447', 'pm_score': 2, 'selected': False, 'text': '<p>I had to clean up a project wich many (duplicate/similar) queries riddled with injection vulnerabilities.\nThe first steps I took were using placeholders and label every query with the object/method and source-line the query was created. \n(Insert the PHP-constants <strong>METHOD</strong> and <strong>LINE</strong> into a SQL comment-line)</p>\n\n<p>It looked something like this:</p>\n\n<blockquote>\n  <p>-- @Line:151 UserClass::getuser():</p>\n\n<pre><code>SELECT * FROM USERS;\n</code></pre>\n</blockquote>\n\n<p>Logging all queries for a short time supplied me with some starting points on which queries to merge. (And where!)</p>\n'}, {'answer_id': 88500, 'author': 'lewis', 'author_id': 14442, 'author_profile': 'https://Stackoverflow.com/users/14442', 'pm_score': 0, 'selected': False, 'text': '<p>I try to use fairly generic functions and just pass the differences in them. This way you only have one function to handle most of your database SELECT\'s. Obviously you can create another function to handle all your INSERTS.</p>\n\n<p>eg.</p>\n\n<pre><code>function getFromDB($table, $wherefield=null, $whereval=null, $orderby=null) {\n    if($wherefield != null) { \n        $q = "SELECT * FROM $table WHERE $wherefield = \'$whereval\'"; \n    } else { \n        $q = "SELECT * FROM $table";\n    }\n    if($orderby != null) { \n        $q .= " ORDER BY ".$orderby; \n    }\n\n    $result = mysql_query($q)) or die("ERROR: ".mysql_error());\n    while($row = mysql_fetch_assoc($result)) {\n        $records[] = $row;\n    }\n    return $records;\n}\n</code></pre>\n\n<p>This is just off the top of my head, but you get the idea. To use it just pass the function the necessary parameters:</p>\n\n<p>eg.</p>\n\n<pre><code>$blogposts = getFromDB(\'myblog\', \'author\', \'Lewis\', \'date DESC\');\n</code></pre>\n\n<p>In this case <em>$blogposts</em> will be an array of arrays which represent each row of the table. Then you can just use a foreach or refer to the array directly:</p>\n\n<pre><code>echo $blogposts[0][\'title\'];\n</code></pre>\n'}, {'answer_id': 89454, 'author': 'Shabbyrobe', 'author_id': 15004, 'author_profile': 'https://Stackoverflow.com/users/15004', 'pm_score': 6, 'selected': True, 'text': '<p>The best course of action for you will depend on how you are approaching your data access. There are three approaches you can take:</p>\n\n<ul>\n<li>Use stored procedures</li>\n<li>Keep the queries in the code (but put all your queries into functions and fix everything to use PDO for parameters, as mentioned earlier)</li>\n<li>Use an ORM tool</li>\n</ul>\n\n<p>If you want to pass your own raw SQL to the database engine then stored procedures would be the way to go if all you want to do is get the raw SQL out of your PHP code but keep it relatively unchanged. The stored procedures vs raw SQL debate is a bit of a holy war, but K. Scott Allen makes an excellent point - albeit a throwaway one - in an article about <a href="http://odetocode.com/blogs/scott/archive/2008/02/02/11737.aspx" rel="nofollow noreferrer">versioning databases</a>: </p>\n\n<blockquote>\n  <p>Secondly, stored procedures have fallen out of favor in my eyes. I came from the WinDNA school of indoctrination that said stored procedures should be used all the time. Today, I see stored procedures as an API layer for the database. This is good if you need an API layer at the database level, but I see lots of applications incurring the overhead of creating and maintaining an extra API layer they don\'t need. In those applications stored procedures are more of a burden than a benefit.</p>\n</blockquote>\n\n<p>I tend to lean towards not using stored procedures. I\'ve worked on projects where the DB has an API exposed through stored procedures, but stored procedures can impose some limitations of their own, and those projects have <em>all</em>, to varying degrees, used dynamically generated raw SQL in code to access the DB. </p>\n\n<p>Having an API layer on the DB gives better delineation of responsibilities between the DB team and the Dev team at the expense of some of the flexibility you\'d have if the query was kept in the code, however PHP projects are less likely to have sizable enough teams to benefit from this delineation.</p>\n\n<p>Conceptually, you should probably have your database versioned. Practically speaking, however, you\'re far more likely to have just your code versioned than you are to have your database versioned. You are likely to be changing your queries when you are making changes to your code, but if you are changing the queries in stored procedures stored against the database then you probably won\'t be checking those in when you check the code in and you lose many of the benefits of versioning for a significant area of your application.</p>\n\n<p>Regardless of whether or not you elect not to use stored procedures though, you should at the very least ensure that each database operation is stored in an independent function rather than being embedded into each of your page\'s scripts - essentially an API layer for your DB which is maintained and versioned with your code. If you\'re using stored procedures, this will effectively mean you have two API layers for your DB, one with the code and one with the DB, which you may feel unnecessarily complicates things if your project does not have separate teams. I certainly do.</p>\n\n<p>If the issue is one of code neatness, there are ways to make code with SQL jammed in it more presentable, and the UserManager class shown below is a good way to start - the class only contains queries which relate to the \'user\' table, each query has its own method in the class and the queries are indented into the prepare statements and formatted as you would format them in a stored procedure.</p>\n\n<pre><code>// UserManager.php:\n\nclass UserManager\n{\n    function getUsers()\n    {\n        $pdo = new PDO(...);\n        $stmt = $pdo-&gt;prepare(\'\n            SELECT       u.userId as id,\n                         u.userName,\n                         g.groupId,\n                         g.groupName\n            FROM         user u\n            INNER JOIN   group g\n            ON           u.groupId = g.groupId\n            ORDER BY     u.userName, g.groupName\n        \');\n        // iterate over result and prepare return value\n    }\n\n    function getUser($id) {\n        // db code here\n    }\n}\n\n// index.php:\nrequire_once("UserManager.php");\n$um = new UserManager;\n$users = $um-&gt;getUsers();\nforeach ($users as $user) echo $user[\'name\'];\n</code></pre>\n\n<p>However, if your queries are quite similar but you have huge numbers of permutations in your query conditions like complicated paging, sorting, filtering, etc, an Object/Relational mapper tool is probably the way to go, although the process of overhauling your existing code to make use of the tool could be quite complicated.</p>\n\n<p>If you decide to investigate ORM tools, you should look at <a href="http://propel.phpdb.org/" rel="nofollow noreferrer">Propel</a>, the ActiveRecord component of <a href="http://yiiframework.com" rel="nofollow noreferrer">Yii</a>, or the king-daddy PHP ORM, <a href="http://www.doctrine-project.org/" rel="nofollow noreferrer">Doctrine</a>. Each of these gives you the ability to programmatically build queries to your database with all manner of complicated logic. Doctrine is the most fully featured, allowing you to template your database with things like the <a href="http://www.developersdex.com/gurus/articles/112.asp" rel="nofollow noreferrer">Nested Set tree pattern</a> out of the box.</p>\n\n<p>In terms of performance, stored procedures are the fastest, but generally not by much over raw sql. ORM tools can have a significant performance impact in a number of ways - inefficient or redundant querying, huge file IO while loading the ORM libraries on each request, dynamic SQL generation on each query... all of these things can have an impact, but the use of an ORM tool can drastically increase the power available to you with a much smaller amount of code than creating your own DB layer with manual queries.</p>\n\n<p><a href="https://stackoverflow.com/questions/37791/how-do-you-manage-sql-queries#38053">Gary Richardson</a> is absolutely right though, if you\'re going to continue to use SQL in your code you should always be using PDO\'s prepared statements to handle the parameters regardless of whether you\'re using a query or a stored procedure. The sanitisation of input is performed for you by PDO.</p>\n\n<pre><code>// optional\n$attrs = array(PDO::ATTR_PERSISTENT =&gt; true);\n\n// create the PDO object\n$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass", $attrs);\n\n// also optional, but it makes PDO raise exceptions instead of \n// PHP errors which are far more useful for debugging\n$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n$stmt = $pdo-&gt;prepare(\'INSERT INTO venue(venueName, regionId) VALUES(:venueName, :regionId)\');\n$stmt-&gt;bindValue(":venueName", "test");\n$stmt-&gt;bindValue(":regionId", 1);\n\n$stmt-&gt;execute();\n\n$lastInsertId = $pdo-&gt;lastInsertId();\nvar_dump($lastInsertId);\n</code></pre>\n\n<p>Caveat: assuming that the ID is 1, the above script will output <code>string(1) "1"</code>. <code>PDO-&gt;lastInsertId()</code> returns the ID as a string regardless of whether the actual column is an integer or not. This will probably never be a problem for you as PHP performs casting of strings to integers automatically.</p>\n\n<p>The following will output <code>bool(true)</code>:</p>\n\n<pre><code>// regular equality test\nvar_dump($lastInsertId == 1); \n</code></pre>\n\n<p>but if you have code that is expecting the value to be an integer, like <a href="http://php.net/manual/en/function.is-int.php" rel="nofollow noreferrer">is_int</a> or PHP\'s <a href="http://au.php.net/manual/en/language.operators.comparison.php" rel="nofollow noreferrer">"is really, truly, 100% equal to"</a> operator:</p>\n\n<pre><code>var_dump(is_int($lastInsertId));\nvar_dump($lastInsertId === 1);\n</code></pre>\n\n<p>you could run into some issues.</p>\n\n<p><strong>Edit:</strong> Some good discussion on stored procedures <a href="https://stackoverflow.com/questions/83419/stored-procedures-a-no-go-in-the-phpmysql-world#84294">here</a></p>\n'}, {'answer_id': 291658, 'author': 'user36670', 'author_id': 36670, 'author_profile': 'https://Stackoverflow.com/users/36670', 'pm_score': 0, 'selected': False, 'text': '<p>Use a ORM framework like QCodo - you can easily map your existing database</p>\n'}, {'answer_id': 430813, 'author': 'Andomar', 'author_id': 50552, 'author_profile': 'https://Stackoverflow.com/users/50552', 'pm_score': 2, 'selected': False, 'text': '<p>I\'d move all the SQL to a separate Perl module (.pm)  Many queries could reuse the same functions, with slightly different parameters.</p>\n\n<p>A common mistake for developers is to dive into ORM libraries, parametrized queries and stored procedures.   We then work for months in a row to make the code "better", but it\'s only "better" in a development kind of way.  You\'re not making any new features!</p>\n\n<p>Use complexity in your code only to address customer needs.</p>\n'}]
['https://Stackoverflow.com/questions/37791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4012/']