API:DBAPI:query
| API Quick reference | |
|---|---|
| Function name: | query |
| Modx versions: | all |
| Input parameters: | (String $sql) |
| Return if successful: | result_resource |
| Return type: | mixed |
| Return on failure: | error |
| Object parents: | DocumentParser->DBAPI |
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.
Examples
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;
Related Functions
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; } }
Notes
It is recommended to use the specific database function to run your queries (such as using $modx->db->select() to perform a SELECT query) instead of using this function, when possible. This function is intended for "internal use only", which means that it is intended for use by the database functions.