public get_results ( string $query = null, string $output = OBJECT ) : mixed | ||
$query | string | SQL query. |
$output | string | Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. With one of the first three, return an array of rows indexed from 0 by SQL result row number. Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively. With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value. Duplicate keys are discarded. |
Результат | mixed | Database query results |
public function get_results($query = null, $output = OBJECT)
{
$this->func_call = "\$db->get_results(\"{$query}\", {$output})";
if ($query) {
$this->query($query);
} else {
return null;
}
$new_array = [];
if ($output == OBJECT) {
// Return an integer-keyed array of row objects
return $this->last_result;
} elseif ($output == OBJECT_K) {
// Return an array of row objects with keys from column 1
// (Duplicates are discarded)
foreach ($this->last_result as $row) {
$var_by_ref = get_object_vars($row);
$key = array_shift($var_by_ref);
if (!isset($new_array[$key])) {
$new_array[$key] = $row;
}
}
return $new_array;
} elseif ($output == ARRAY_A || $output == ARRAY_N) {
// Return an integer-keyed array of...
if ($this->last_result) {
foreach ((array) $this->last_result as $row) {
if ($output == ARRAY_N) {
// ...integer-keyed row arrays
$new_array[] = array_values(get_object_vars($row));
} else {
// ...column name-keyed row arrays
$new_array[] = get_object_vars($row);
}
}
}
return $new_array;
} elseif (strtoupper($output) === OBJECT) {
// Back compat for OBJECT being previously case insensitive.
return $this->last_result;
}
return null;
}
/** * Bind model to database table * @param string $tableName * @return PMXI_Model */ public function setTable($tableName) { if (!is_null($this->table)) { throw new Exception('Table name cannot be changed once being set.'); } $this->table = $tableName; if (!isset(self::$meta_cache[$this->table])) { $tableMeta = $this->wpdb->get_results("SHOW COLUMNS FROM {$this->table}", ARRAY_A); $primary = array(); $auto_increment = false; foreach ($tableMeta as $colMeta) { if ('PRI' == $colMeta['Key']) { $primary[] = $colMeta['Field']; } if ('auto_increment' == $colMeta['Extra']) { $auto_increment = true; break; // no point to iterate futher since auto_increment means corresponding primary key is simple } } self::$meta_cache[$this->table] = array('primary' => $primary, 'auto_increment' => $auto_increment); } $this->primary = self::$meta_cache[$this->table]['primary']; $this->auto_increment = self::$meta_cache[$this->table]['auto_increment']; return $this; }