Querying the Database


This function will send a given query string to the database. However, it is mainly for internal use. Developers should use select, update, insert and delete where possible.

The function:

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>
";
    }     $modx->executedQueries = $modx->executedQueries+1;     return $result;   } }

To use

$sql = "sql_string";
$results = $modx->db->query($sql);

The $results returned from a query may or may not be of any use; although it can usually be used to determine success or failure.

Example

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

This will empty the given table.