query

API:DB:query

API Quick reference
Variable name: query
Modx versions: 0.9.x + Evolution
Input parameters: (String $sql)
Return if successful: result_resource
Return type: mixed
Return on failure: error
Object parent: DocumentParser -> DBAPI

Description

mixed query(String $sql)

This function is used by all of the MODx functions that run queries on your database (such as select() or update(). It takes a String as a parameter, which contains the full SQL query that should be run on your database. Essentially, the DBAPI functions that query the database build a query based on the arguments passed to it, and then use this function to actually query the database.

Usage / Examples

function login($username, $password)
The following function will SELECT data from a users table and output it to the page:

$output = '';
$result = $modx->db->query( 'SELECT id, name, joined FROM `user_table` GROUP BY `member_type` ORDER BY name ASC' );

while( $row = $modx->db->getRow( $result ) ) {
        $output .= '<br /> ID: ' . $row['id'] . '<br /> Name: ' . $row['name'] . '<br /> Joined: ' . $row['joined']
        . '<br />---------<br />';
}
echo $output;

Example2:

$table = $modx->getFullTableName("table_name");
$sql = "TRUNCATE TABLE $table";
$modx->db->query($sql);

This will empty the given table.

conn, select(), update(), delete(), [getAffectedRows](), [getRow](), [makeArray]().

Function Source

File: manager/includes/extenders/dbapi.class.inc.php
Line: 131

function query($sql) {
      global $modx;
      if (empty ($this->conn) || !is_resource($this->conn)) {
         $this->connect();
      }
      $tstart = $modx->getMicroTime();
      if (!$result = @ mysql_query($sql, $this->conn)) {
         $modx->messageQuit("Execution of a query to the database failed - " . $this->getLastError(), $sql);
      } else {
         $tend = $modx->getMicroTime();
         $totaltime = $tend - $tstart;
         $modx->queryTime = $modx->queryTime + $totaltime;
         if ($modx->dumpSQL) {
            $modx->queryCode .= "<fieldset style='text-align:left'><legend>Query " . ($this->executedQueries + 1) . " - " . sprintf("%2.4f s", $totaltime) . "</legend>" . $sql . "</fieldset><br />";
         }
         $modx->executedQueries = $modx->executedQueries + 1;
         return $result;
      }
   }

Suggest an edit to this page on GitHub (Requires GitHub account. Opens a new window/tab).