API:DBAPI:select

From MODx Wiki

Jump to: navigation, search
API Quick reference
Function name: select
Modx versions: >0.9.2
Input parameters: ([string $fields [, string $from [, string $where [, string $orderby [, string $limit]]]]])
Return if successful: resource
Return type: resource
Return on failure: false
Object parents: DocumentParser->DBAPI
resource select([string $fields [, string $from [, string $where [, string $orderby [, string $limit]]]]])


select() sends a query to the currently active database, $this->conn as created when connect() is called. This function is analogous to mysql_query() except the query string is broken up into 5 parts. Only the $from field is required for a meaningful result.

Parameter $fields are the field or column name(s) that you want returned. If left blank it will default to all (*).

$from is the table to query. If left blank function will return false.

$where is the full string of the WHERE clause of the mysql query. Leave blank to do no WHERE matching.

$orderby, if needed, can either be 'ASC' or 'DESC'.

$limit is the limit of the number of results to return, leave blank for all.

Examples

This example login function uses the select function to get the id of a user given the username and password.

function login($username, $password)
{
   global $modx, $table_prefix;
   $username = $modx->db->escape($username);
   $password = $modx->db->escape($password);
 
   $res = $modx->db->select("id", $table_prefix.".modx_web_users", 
      "username='$username' AND password='".md5($password)."'");
   if($modx->db->getRecordCount($res))
   {
      $_SESSION['userid'] = $id;
      //other log in things...
   }
   else
   {
      //incorrect login
   }
}

Related Functions

getRecordCount(), query(), getRow(), makeArray()

Function source

File: manager/includes/extenders/dbapi.class.inc.php
Line: 169
function select($fields = "*", $from = "", $where = "", $orderby = "", $limit = "") {
   if (!$from)
      return false;
   else {
      $table = $from;
      $where = ($where != "") ? "WHERE $where" : "";
      $orderby = ($orderby != "") ? "ORDER BY $orderby " : "";
      $limit = ($limit != "") ? "LIMIT $limit" : "";
      return $this->query("SELECT $fields FROM $table $where $orderby $limit");
   }
}

Notes

One could easily use mysql_query($qry) instead of this function, however it is preferred to use this function, especially for modx table calls, to ensure future compatibility should their be any changes to the way modx queries the database (eg: changing to mysqli_query(), or using another database type altogether).

Personal tools