Zikula_Core
[ class tree: Zikula_Core ] [ index: Zikula_Core ] [ all elements ]

Source for file queryutil.php

Documentation is available at queryutil.php

  1. <?php
  2. /**
  3.  * Zikula Application Framework
  4.  *
  5.  * @copyright (c) 2001, Zikula Development Team
  6.  * @link http://www.zikula.org
  7.  * @version $Id: queryutil.php 24342 2008-06-06 12:03:14Z markwest $
  8.  * @license GNU/GPL - http://www.gnu.org/copyleft/gpl.html
  9.  * @package Zikula_Core
  10.  * @subpackage Zikula_legacy
  11.  */
  12.  
  13. /**
  14.  * This method escapes strings appropriately for the 'dbtype'
  15.  * database currently in use.  No "unescaping" is necessary when you
  16.  * pull it out since the result strings are un-escaped anyway.
  17.  *
  18.  * Takes a string arg and returns a string argument escaped for the
  19.  * appropriate database or processed through the addslashes method
  20.  * if no database-specific method found.
  21.  */
  22. function dbescape ($textstring)
  23. {
  24.     // just in case it's been slashed
  25.     $textstring stripslashes ($textstring);
  26.  
  27.     return pnVarPrepForStore($textstring);
  28. }
  29.  
  30. /**
  31.  * getAllColumns
  32.  *
  33.  * returns a string containing the fully qualified column names for a
  34.  * select, insert, or update statement.  The order is not guaranteed,
  35.  * however.  The safest use for this is where you would use a "SELECT *"
  36.  * query.  Separating whitespace is automatically added for safety.
  37.  *
  38.  * for example: if the table 'example' has columns 'id', and 'name'
  39.  * a call of:
  40.  *
  41.  * $sel = getAllColumns('example');
  42.  *
  43.  * would resulting in $sel having the value:
  44.  *
  45.  * " example.id as \"id\", example.name AS \"name\" "
  46.  *
  47.  * see: getAllColumnsFrom for inclusion of the tablename
  48.  *      getSelectAllColumnsFrom for inclusion of select and tablename
  49.  *      getColumnsViaHashKeys for grabbing a specific set of columns
  50.  *      buildSimpleQuery for building a query on one table in a single call
  51.  *      buildQuery for building a join query in a single call
  52.  */
  53. function getAllColumns($tablename)
  54. {
  55.     // get the table information
  56.     $pntable pnDBGetTables();
  57.     return getColumnsViaHashKeys($tablename$pntable["{$tablename}_column"]);
  58. }
  59.  
  60. /**
  61.  * getSelectAllColumns
  62.  *
  63.  * prepends "SELECT" to the value returned from getAllColumns
  64.  */
  65. function getSelectAllColumns($tablename)
  66. {
  67.     // use the other method and append a FROM clause
  68.     $query "SELECT" getAllColumns($tablename);
  69.  
  70.     return $query;
  71. }
  72.  
  73. /**
  74.  * getAllColumnsFrom
  75.  *
  76.  * adds "FROM $pntable[$tablename] " to the value returned from
  77.  * getAllColumns
  78.  *
  79.  * also adds an optional WHERE class to be automatically added
  80.  */
  81. function getAllColumnsFrom($tablename$whereclause '')
  82. {
  83.     // get the table information
  84.     $pntable pnDBGetTables();
  85.  
  86.     // use the other method and append a FROM clause
  87.     $query getAllColumns($tablename"FROM $pntable[$tablename] ";
  88.     if ($whereclause{
  89.         $query .= "WHERE $whereclause";
  90.     }
  91.  
  92.     return $query;
  93. }
  94.  
  95. /**
  96.  * getSelectAllColumnsFrom
  97.  *
  98.  * prepends "SELECT" to the value returned from getAllColumnsFrom
  99.  *
  100.  * also adds an optional WHERE class to be automatically added
  101.  */
  102. function getSelectAllColumnsFrom($tablename$whereclause '')
  103. {
  104.     // use the other method and append a FROM clause
  105.     $query "SELECT" getAllColumnsFrom($tablename$whereclause);
  106.  
  107.     return $query;
  108. }
  109.  
  110. /**
  111.  * buildSimpleQuery
  112.  *
  113.  * This is a simplified version of buildQuery for use on one table.  The
  114.  * arguments are specified as strings in most cases instead of arrays.
  115.  *
  116.  * Example:  The following db abstract code -
  117.  *
  118.  * $column = $pntable['authors_column'];
  119.  * $result = $dbconn->query ("SELECT $column[aid], $column[name]
  120.  *                               FROM $pntable['authors']
  121.  *                               WHERE $column[radminarticle]=1
  122.  *                               ORDER BY $column[aid]
  123.  *                               LIMIT 1");
  124.  *
  125.  * Could be re-written as:
  126.  *
  127.  * $column = $pntable['authors_column'];
  128.  * $myquery = buildSimpleQuery ('authors', array ('aid', 'name'), "$column[radminarticle]=1", "$column[aid]", 1);
  129.  * $result = $dbconn->query($myquery);
  130.  *
  131.  * (you could, of course, skip storing the string in $myquery...but for
  132.  *   illustration I included it)
  133.  *
  134.  * The nice thing about using this is that it takes care of db-specific
  135.  * ways of handling the "LIMIT" clause because it uses buildQuery internally.
  136.  *
  137.  * ARGUMENTS:
  138.  *   Strings: $tablename  = $pntable mapping name
  139.  *            $where      = WHERE clause conditions ('WHERE' added automatically)
  140.  *            $orderby    = ORDERBY sort order ('ORDER BY' added automatically)
  141.  *
  142.  *   int:     $limitmax   = The maximum number of rows to return
  143.  *            $limitmin   = the offset in the result set to start at
  144.  *
  145.  *   array:   $columnames = array of $pntable mapping names to return from the query
  146.  */
  147. function buildSimpleQuery($tablename$columnnames$where ''$orderby ''$limitmax ''$limitmin '')
  148. {
  149.     // get the database connection
  150.     $dbconn pnDBGetConn(true);
  151.     $pntable pnDBGetTables();
  152.  
  153.     if ($orderby{
  154.         $orderby array($orderby);
  155.     }
  156.     // pull out fully qualified columnnames
  157.     $column $pntable["{$tablename}_column"];
  158.     foreach ($columnnames as $idx => $name{
  159.         $columnnames[$idx"$column[$name] AS \"$name\"";
  160.     }
  161.     return buildQuery (array($tablename)$columnnames$where$orderby$limitmax$limitmin);
  162. }
  163.  
  164. /**
  165.  * buildSimpleQuery
  166.  *
  167.  * This can build a fairly complex query in a cross-database fashion.
  168.  * It takes arrays for most of the fields and converts it into a
  169.  * fully-qualified SQL query for the database held in $pnconfig['dbtype']
  170.  *
  171.  * Example:  The following db abstract code -
  172.  *
  173.  * $authorscolumn = $pntable['authors_column'];
  174.  * $storiescolumn = $pntable['stories_column'];
  175.  * $result = $dbconn->query ("SELECT $authorscolumn[aid],
  176.  *                                    $authorscolumn[name],
  177.  *                                    $storiescolumn[title]
  178.  *                               FROM $pntable['authors'], $pntable['stories']
  179.  *                               WHERE $authorscolumn[aid]=$storiescolumn[aid]
  180.  *                                 AND $authorscolumn[aid]='$aid'
  181.  *                               ORDER BY $storiescolumn[time] DESC
  182.  *                               LIMIT 2, 4");
  183.  *
  184.  * Could be re-written as:
  185.  *
  186.  * $authorscolumn = $pntable['authors_column'];
  187.  * $storiescolumn = $pntable['stories_column'];
  188.  * $myquery = buildQuery (array ('authors', 'stories',
  189.  *                         array ($authorscolumn[aid], $authorscolumn[name], $storiescolumn[title]),
  190.  *                         "$authorscolumn[aid]=$storiescolumn[aid] AND $authorscolumn[aid]='$aid'",
  191.  *                         "$storiescolumn[time] DESC",
  192.  *                         4, 2);
  193.  * $result = $dbconn->query($myquery);
  194.  *
  195.  * (you could, of course, skip storing the string in $myquery...but for
  196.  *   illustration I included it)
  197.  *
  198.  * The nice thing about using this is that it takes care of db-specific
  199.  * ways of handling the "LIMIT" clause because it uses buildQuery internally.
  200.  *
  201.  * ARGUMENTS:
  202.  *   array:   $tablenames = array of $pntable mapping names
  203.  *            $columnames = array of fully qualified column names (table.column)
  204.  *            $orderby    = ORDERBY sort order ('ORDER BY' added automatically)
  205.  *                          sort order is based on indeces:
  206.  *                            ORDER BY $orderby[0], $orderby[1]...
  207.  *
  208.  *   string:  $where      = WHERE clause conditions ('WHERE' added automatically)
  209.  *
  210.  *   int:     $limitmax   = The maximum number of rows to return
  211.  *            $limitmin   = the offset in the result set to start at
  212.  */
  213. function buildQuery($tablenames$columnnames$where ''$orderby ''$limitmax ''$limitmin '')
  214. {
  215.     // get the database connection
  216.     $dbconn pnDBGetConn(true);
  217.     $pntable pnDBGetTables();
  218.  
  219.     $tables "";
  220.     for ($i 0$i sizeof($tablenames)$i ++{
  221.         if ($i 0{
  222.             $tables .= ",";
  223.         }
  224.         $tables .= " {$pntable[$tablenames[$i]]}";
  225.     }
  226.  
  227.     $columns "";
  228.     for ($i 0$i sizeof($columnnames)$i ++{
  229.         if ($i 0{
  230.             $columns .= ",";
  231.         }
  232.         $columns .= " {$columnnames[$i]}";
  233.     }
  234.  
  235.     $orders "";
  236.     if ($orderby{
  237.         for ($i 0$i sizeof($orderby)$i ++{
  238.             if ($i 0{
  239.                 $orders .= ",";
  240.             }
  241.             $orders .= " {$orderby[$i]}";
  242.         }
  243.     }
  244.     if (strcmp(pnConfigGetVar('dbtype')'oci8'== 0{
  245.         $query "SELECT $columns FROM $tables ";
  246.         if (($whereand ($limitmax)) {
  247.             if ($limitmin{
  248.                 $query .= " WHERE $where AND (rownum >= $limitmin AND rownum <= $limitmax)";
  249.             else {
  250.                 $query .= " WHERE $where AND rownum <= $limitmax";
  251.             }
  252.         elseif ($where{
  253.             $query .= " WHERE $where ";
  254.         elseif ($limitmax{
  255.             if ($limitmin{
  256.                 $query .= " WHERE rownum >= $limitmin AND rownum <= $limitmax";
  257.             else {
  258.                 $query .= " WHERE rownum <= $limitmax";
  259.             }
  260.         }
  261.         if ($orders{
  262.             $query .= " ORDER BY $orders ";
  263.         }
  264.     else // Assume MySQL standard
  265.         $query "SELECT $columns FROM $tables ";
  266.         if ($where{
  267.             $query .= " WHERE $where ";
  268.         }
  269.         if ($orders{
  270.             $query .= " ORDER BY $orders ";
  271.         }
  272.         if ($limitmax{
  273.             if ($limitmin{
  274.                 $query .= " LIMIT $limitmin,$limitmax";
  275.             else {
  276.                 $query .= " LIMIT $limitmax";
  277.             }
  278.         }
  279.     }
  280.  
  281.     return $query;
  282. }
  283.  
  284. /**
  285.  * Gets a list of column names, properly quoted for associative array use
  286.  * later on based on the keys in the column_key_hash variable.  For
  287.  * example, if:
  288.  *
  289.  * $tablename = 'downloads_newdownload'
  290.  * $column_key_hash = array ('lid' => '');
  291.  *
  292.  * then
  293.  *
  294.  * this will return (assuming the orig, default column name mappings):
  295.  *
  296.  *
  297.  * "{$prefix}_downloads_newdownload.lid as \"lid\""
  298.  *
  299.  * This ensures that associative array mappings will be correct since even
  300.  * case-insensitive databases such as oracle respect your "AS" naming if
  301.  * it is enclosed in literal quotes.
  302.  *
  303.  * fifers: should probably base this on an indexed array instead...
  304.  */
  305. function getColumnsViaHashKeys($tablename$column_key_hash)
  306. {
  307.     // get the table information
  308.     $pntable pnDBGetTables();
  309.  
  310.     // init our vars
  311.     $query '';
  312.     // grab each key and value and append the values
  313.     $column $pntable["{$tablename}_column"];
  314.     foreach ($column_key_hash as $key => $val{
  315.         $query .= " $column[$key] AS \"$key\",";
  316.     }
  317.     // remove the last ',' from our built result...if there is any
  318.     // length - 1 is the last pos in our string, the ','
  319.     if (($length strlen($query)) 0{
  320.         $query substr($query0$length 1);
  321.         // add our trailing space
  322.         $query "$query ";
  323.     }
  324.  
  325.     return $query;
  326. }
  327.  
  328. /**
  329.  * Returns a statement of the form:
  330.  *
  331.  * tablename.hashval1 as \"hashkey1\", ...
  332.  *
  333.  * based on the KEYS in the $column_key_hash variable.  useful to build a
  334.  * query that only needs a couple of columns returned.
  335.  *
  336.  * fifers: should probably base this on an indexed array instead...
  337.  */
  338. function getColumnsViaHashKeysFrom($tablename$column_key_hash$whereclause '')
  339. {
  340.     // get the table information
  341.     $pntable pnDBGetTables();
  342.  
  343.     $query getColumnsViaHashKeys ($tablename$column_key_hash"FROM $pntable[$tablename] ";
  344.     if (!empty($whereclause)) {
  345.         $query .= "WHERE $whereclause";
  346.     }
  347.  
  348.     return $query;
  349. }
  350.  
  351. /**
  352.  * This adds the SELECT to the front of the getColumnsViaHashKeysFrom
  353.  * method's returned value.
  354.  */
  355. function getSelectViaHashKeysFrom($tablename$column_key_hash$whereclause '')
  356. {
  357.     // get the table information
  358.     $pntable pnDBGetTables();
  359.  
  360.     $query "SELECT " getColumnsViaHashKeysFrom($tablename$column_key_hash$whereclause);
  361.  
  362.     return $query;
  363. }
  364.  
  365. /**
  366.  * This method is simply for naming convenience.  It could be eliminated
  367.  * since it merely calls getSelectViaHashKeysFrom and returns what it
  368.  * returns.  If you follow the naming conventions I used in this file,
  369.  * however, it must exist for consistency!
  370.  */
  371. function getSelectColumnsViaHashKeysFrom($tablename$column_key_hash$whereclause '')
  372. {
  373.     return (getSelectViaHashKeysFrom($tablename$column_key_hash$whereclause));
  374. }

Documentation generated on Fri, 18 Jul 2008 21:56:33 +0200 by phpDocumentor 1.4.1