/** * @inheritdoc */ public function quoteIdentifier($identifier) { if (!is_resource($this->resource)) { $this->connect(); } return pg_escape_identifier($this->resource, $identifier); }
function escapeIdentifier($string) { if (version_compare(PHP_VERSION, "5.4", "<")) { return '"' . $string . '"'; } else { self::connect(); return pg_escape_identifier($this->connection, $string); } }
public function __call($name, array $arguments) { // converting camel cast to snake case (underscore) and escaping $table = pg_escape_identifier(strtolower(preg_replace('/([a-z0-9])([A-Z])/', '${1}_${2}', $name))); $params = array(); foreach ($arguments as $v) { $params[] = is_null($v) ? 'null' : "'" . pg_escape_string($v) . "'"; } $sql = 'SELECT * FROM ' . pg_escape_identifier(self::$schema) . '.' . $table . '(' . implode(',', $params) . ')'; if ($res = @pg_query(self::$connection, $sql)) { return new Result($res); } $err = error_get_last(); if (empty($err['message'])) { $message = "Query failed: {$sql}"; } else { $message = html_entity_decode(preg_replace('/.+?ERROR:\\s*(.+)/', '${1}', $err['message'])); } throw new Exception($message); }
/** * escape identifiers for SQL statements * * @param string $str * @return string */ public static function ident($str) { return pg_escape_identifier($str); }
public function escapeIdentifier($value, $separator = '.') { if (empty($separator) && function_exists('pg_escape_identifier')) { return pg_escape_identifier($this->dbConn, $value); } // Let parent function handle recursive calls return parent::escapeIdentifier($value, $separator); }
public function update($tablename, array $update_record, array $where_record) { assert(is_string($tablename)); assert(strlen($tablename) > 0); assert(is_array($update_record)); assert(count($update_record) > 0); assert(is_array($where_record)); assert(count($where_record) > 0); $result = $this->query("UPDATE " . pg_escape_identifier($tablename) . " SET " . self::record_to_sql($update_record, ' , ', true) . " WHERE " . self::record_to_sql($where_record, ' AND ')); // chop first ',' if ($result->affected_rows() != 1) { throw new DatabaseUpdateException(); } return $result; }
// Force bytea escaping and retry @pg_query($db, "SET bytea_output = 'escape'"); } else { $result = pg_query($db, $sql); echo "pg_escape_bytea() is broken\n"; break; } } // pg_escape_literal/pg_escape_identifier $before = "ABC\\ABC\\'"; $expect = " E'ABC\\\\ABC\\\\'''"; $after = pg_escape_literal($before); if ($expect === $after) { echo "pg_escape_literal() is Ok\n"; } else { echo "pg_escape_literal() is NOT Ok\n"; var_dump($before); var_dump($after); var_dump($expect); } $before = "ABC\\ABC\\'"; $expect = "\"ABC\\ABC\\'\""; $after = pg_escape_identifier($before); if ($expect === $after) { echo "pg_escape_identifier() is Ok\n"; } else { echo "pg_escape_identifier() is NOT Ok\n"; var_dump($before); var_dump($after); var_dump($expect); }
public function convertToSql($value, $type) { switch ($type) { case self::TYPE_STRING: return pg_escape_literal($this->connection, $value); case self::TYPE_BOOL: return $value ? 'TRUE' : 'FALSE'; case self::TYPE_IDENTIFIER: $parts = explode('.', $value); foreach ($parts as &$part) { if ($part !== '*') { $part = pg_escape_identifier($this->connection, $part); } } return implode('.', $parts); case self::TYPE_DATETIME: if ($value->getTimezone()->getName() !== $this->connectionTz->getName()) { $value = clone $value; $value->setTimezone($this->connectionTz); } return "'" . $value->format('Y-m-d H:i:s') . "'"; case self::TYPE_DATETIME_SIMPLE: if ($value->getTimezone()->getName() !== $this->simpleStorageTz->getName()) { $value = clone $value; $value->setTimezone($this->simpleStorageTz); } return "'" . $value->format('Y-m-d H:i:s') . "'"; case self::TYPE_DATE_INTERVAL: return $value->format('P%yY%mM%dDT%hH%iM%sS'); case self::TYPE_BLOB: return "'" . pg_escape_bytea($this->connection, $value) . "'"; default: throw new InvalidArgumentException(); } }
/** * @param string $identifier * * @return string */ public function escapeIdentifier($identifier) { return pg_escape_identifier($this->handler, $identifier); }
public function rollback() { if ($this->transaction_complete) { throw new DatabaseException("Transaction already finished"); } if ($this->using_savepoints) { $this->parent_connection->query('ROLLBACK TRANSACTION TO SAVEPOINT ' . pg_escape_identifier($this->savepoint_name)); $this->parent_connection->query('RELEASE SAVEPOINT ' . pg_escape_identifier($this->savepoint_name)); } else { $this->parent_connection->query('ROLLBACK TRANSACTION'); } $this->transaction_complete = true; }
/** * Quote a table with the appropriate characters for this mode */ protected function quoteTable($table) { # The odbc sql only uses it's quote strings for renaming fields, not for quoting table/field names if ($this->mode == "odbc") { return $table; } $table = trim($table); # There is a standard function for quoting postgres table names if (in_array($this->mode, ["postgres", "redshift"], true)) { $this->connect(); return pg_escape_identifier($this->server, $table); } $chars = $this->quoteChars[$this->mode]; if (is_array($chars)) { $from = $chars[0]; $to = $chars[1]; } else { $from = $chars; $to = $chars; } $quoted = $from . $table . $to; return $quoted; }
function handle_message(&$websocket, $client, $message) { global $database; global $client_names; global $client_numbers; global $fragments; echo "{$client} |==> {$message} <==|\n"; if ($message[0] == '?') { $resp = file_get_contents("test.dat"); websocket_send($websocket, $client, '!'); websocket_send($websocket, $client, $resp); return; } if ($message[0] == "-") { if (!array_key_exists($client, $fragments)) { $fragments[$client] = ""; } $fragments[$client] .= substr($message, 1); websocket_send($websocket, $client, "&"); return; } else { if ($message[0] == "%") { if (array_key_exists($client, $fragments) && $fragments[$client] != "") { websocket_send($websocket, $client, "&"); } return; } else { if ($message[0] == "+") { if (array_key_exists($client, $fragments) && $fragments[$client] != "") { $message = $fragments[$client] . substr($message, 1); $fragments[$client] = ""; } else { $message = substr($message, 1); } } } } $args = NULL; $action = NULL; $name = NULL; $data = NULL; $links = NULL; $assets = NULL; $asset = NULL; $error = NULL; $ans = NULL; $res = NULL; $clients = NULL; if ($message[0] != '{') { $error = 'an object expected'; $args = array(); } else { $args = json_decode($message, true); if (!$args) { $error = 'JSON error ' . json_last_error() . ': ' . json_last_error_msg(); $args = array(); } } if (isset($args['action'])) { $action = $args['action']; } else { if (!$error) { $error = 'no "action" property specified'; } } if (isset($args['client'])) { $name = $args['client']; } if (!$error && isset($args['data'])) { $data = $args['data']; if (!is_array($data)) { $error = 'property "data" is not an object'; } else { if (!$name && isset($data['client'])) { $name = $data['client']; } if (isset($data['connections'])) { $links = array(); foreach ($data['connections'] as $other) { $links[$other] = TRUE; } unset($data['connections']); } if (isset($data['assets'])) { $assets = array(); foreach ($data['assets'] as $asset) { $assets[$asset] = TRUE; } unset($data['assets']); } } } if (isset($args['asset'])) { $asset = $args['asset']; } if ($error) { // error, do nothing } else { if (!is_string($action)) { $error = 'action is not a string'; } else { if ($action == 'set') { if (!$name) { $error = 'no "client" specified'; } else { $query = ""; $result = FALSE; $esc_name = escape_literal($name); if (isset($links)) { $query = 'DELETE FROM links WHERE a = ' . $esc_name . ' OR b = ' . $esc_name . ';'; $newlinks = ""; foreach ($links as $other => $val) { $newlinks .= ', (' . $esc_name . ',' . escape_literal($other) . ')'; } if ($newlinks != "") { $query .= 'INSERT INTO links (a, b) VALUES' . substr($newlinks, 1) . ';'; } $result = pg_query($database, $query); if ($result === FALSE) { $error = pg_last_error($database); } } if ($data && !$error) { $query = ''; foreach ($data as $key => $val) { $query .= ', ' . pg_escape_identifier($key) . ' = ' . escape_literal($val); } if (strlen($query) > 1) { $query = 'UPDATE clients SET' . substr($query, 1) . ' WHERE client = ' . escape_literal($name) . ';'; $result = pg_query($database, $query); if (!$result) { $error = pg_last_error($database); } else { if (pg_affected_rows($result) < 1) { $result = FALSE; } } } } if (!$error && !$result) { if ($name) { if (!$data) { $data = array('client' => $name); } else { if (!isset($data['client'])) { $data['client'] = $name; } } } if (isset($data['client'])) { $keys = ''; $vals = ''; foreach ($data as $key => $val) { $keys .= ', ' . pg_escape_identifier($key); $vals .= ', ' . escape_literal($val); } $query = 'INSERT INTO clients (' . substr($keys, 2) . ') VALUES (' . substr($vals, 2) . ');'; $result = pg_query($database, $query); if (!$result) { $error = pg_last_error($database); } } } } } else { if ($action == 'get') { if ($name) { if (!isset($data['client'])) { $data['client'] = $name; } else { if ($data['client'] != $name) { $error = 'two clients specified'; } } } $res = NULL; if (!$error) { $filter = ''; if (!empty($data)) { foreach ($data as $key => $val) { $filter .= ' AND ' . pg_escape_identifier($database, $key) . ' = ' . escape_literal($val); } $filter = ' WHERE' . substr($filter, 4); } $query = 'SELECT * FROM clients' . $filter . ';'; $result = pg_query($database, $query); if ($result === FALSE) { $error = pg_last_error($database); } else { $res = pg_fetch_all($result); pg_free_result($result); } } if (!$res) { $res = array(); } if (!$error) { $result = pg_query($database, 'SELECT * FROM links;'); if ($result === FALSE) { $error = pg_last_error($database); } else { $links = pg_fetch_all($result); pg_free_result($result); $m = count($res); $n = count($links); for ($i = 0; $i < $m; $i++) { $name_i = $res[$i]['client']; $links_i = array(); for ($j = 0; $j < $n; $j++) { if ($links[$j]['a'] == $name_i) { $links_i[$links[$j]['b']] = 1; } else { if ($links[$j]['b'] == $name_i) { $links_i[$links[$j]['a']] = 1; } } } $res[$i]['connections'] = array_keys($links_i); } } } if (!$error) { $query = 'SELECT * FROM assets'; if ($name) { $query .= ' WHERE "client" = ' . escape_literal($name); } $result = pg_query($database, $query); $assets = array(); $n = pg_num_rows($result); for ($i = 0; $i < $n; $i++) { $name_i = pg_fetch_result($result, $i, 'client'); $asset_i = pg_fetch_result($result, $i, 'asset'); if (!isset($assets[$name_i])) { $assets[$name_i] = array(); } $assets[$name_i][] = $asset_i; } $n = count($res); for ($i = 0; $i < $n; $i++) { $name_i = $res[$i]['client']; if (isset($assets[$name_i])) { $res[$i]['assets'] = $assets[$name_i]; } else { $res[$i]['assets'] = array(); } } } } else { if ($action == 'ask_asset') { $logmsg = NULL; $settings = get_settings(); $random = TRUE; foreach ($settings as $setting) { if ($setting['key'] == 'random') { $val = $setting['value']; $random = $val[0] != 'F' && $val[0] != 'f'; } } $clients = array(); $info = NULL; $result = pg_query($database, 'SELECT * FROM clients;'); if ($result === FALSE) { $error = pg_last_error($database); } else { $info = pg_fetch_all($result); pg_free_result($result); $m = count($info); $query = 'SELECT * FROM links;'; $result = pg_query($database, $query); if ($result === FALSE) { $error = pg_last_error($database); } else { $links = pg_fetch_all($result); pg_free_result($result); $n = count($links); $my_i = -1; $weights = get_algorithm_weights(); use_algorithm_weights($weights); for ($i = 0; $i < $m; $i++) { $name_i = $info[$i]['client']; if ($name_i == $name) { $my_i = $i; } $links_i = array(); for ($j = 0; $j < $n; $j++) { if ($links[$j]['a'] == $name_i) { $links_i[$links[$j]['b']] = 1; } else { if ($links[$j]['b'] == $name_i) { $links_i[$links[$j]['a']] = 1; } } } $info[$i]['connections'] = array_keys($links_i); } if ($my_i >= 0) { $scores = array(); for ($i = 0; $i < $m; $i++) { $info_i = $info[$i]; if ($i != $my_i && isset($client_numbers[$info_i['client']])) { if ($random) { $score_i = mt_rand(0, mt_getrandmax()); } else { $score_i = score($info[$my_i], $info_i); } if ($score_i >= 0) { $scores[$info_i['client']] = $score_i; } } } arsort($scores); $clients = array_keys($scores); } if ($random) { $logmsg = "asset source random selection"; } else { $logmsg = "asset source selection"; } } } if ($logmsg != NULL) { $n = count($clients); if ($n > 5) { $clients = array_slice($clients, 0, 5); } $n = count($clients); $log_data = array(); $log_data['client'] = $name; $log_data['weights'] = $weights; if ($n > 0) { $sum_battery = 0; $sum_speed = 0; for ($i = 0; $i < $m; $i++) { if (array_search($info[$i]['client'], $clients) !== FALSE) { if ($info[$i]['battery_charging'][0] == 't') { $sum_battery += 100; } else { $sum_battery += $info[$i]['battery_level']; } $sum_speed += $info[$i]['client_processing_speed']; } } $log_data['avg_battery'] = number_format($sum_battery / $n, 0, '.', ''); $log_data['avg_speed'] = number_format($sum_speed / $n, 1, '.', ''); } $log_data['peers'] = $clients; log_message($name, $logmsg, $log_data); } } else { if ($action == 'delete') { if (!isset($name)) { $error = 'no "client" property'; } else { if (isset($data)) { $error = 'extraneous "data" property'; } else { $esc_name = escape_literal($name); $query = 'DELETE FROM clients WHERE client = ' . $esc_name . ';'; $result = pg_query($database, $query); if ($result === FALSE) { $error = pg_last_error($database); } else { if (pg_affected_rows($result) < 1) { $error = 'client ' . $args['client'] . ' not found'; } pg_free_result($result); } $query = 'DELETE FROM links WHERE a = ' . $esc_name . ' OR b = ' . $esc_name . ';'; $result = pg_query($database, $query); if ($result === FALSE) { $error = pg_last_error($database); } } } } else { if ($action == 'clear') { if (isset($name)) { $error = 'extraneous "client" property'; } else { if (isset($data)) { $error = 'extraneous "data" property'; } else { $result = pg_query($database, 'DELETE FROM clients;'); if ($result === FALSE) { $error = pg_last_error($database); } else { $ans = pg_affected_rows($result); pg_free_result($result); } pg_query($database, "VACUUM FULL clients;"); } } } else { if ($action == 'name') { if (isset($name)) { set_client($client, $name); } else { $ans = NULL; $guess = -1; while ($ans == NULL) { if ($guess < 0) { if (isset($client_names[$client])) { $ans = $client_names[$client]; } } else { if ($guess == 0) { $ans = 'client_' . $client; } else { $letter = chr(0x61 + ($guess - 1) % 26); $num = ($guess - 1) / 26; $ans = 'client_' . $client . $letter . ($num > 0 ? $num : ''); if (isset($client_numbers[$ans])) { if ($client_numbers[$ans] != $client) { $ans = NULL; } } } } $guess++; } } } else { if ($action == 'version') { $ans = date("Y-m-d G:i:s", filemtime("Server.php")); } else { if ($action == 'log') { log_message($name, $args['message'], $data); } else { if ($action == 'clear_log') { $text = date("Y-m-d G:i:s") . "\n"; $text .= "========================================\n"; file_put_contents("Server_log.txt", $text, LOCK_EX); } else { if ($action == 'say') { if (!isset($client_names[$client])) { $error = 'Client name not set'; } else { $msg = $args; $msg['action'] = "said"; $msg['client'] = $client_names[$client]; $msge = json_encode($msg); if (isset($name)) { if (isset($client_numbers[$name])) { websocket_send($websocket, $client_numbers[$name], $msge); } else { $error = 'Client "' . $name . '" not known'; } } else { websocket_send_others($websocket, $client, $msge); } } } else { if ($action == 'terminate') { websocket_shutdown($websocket); // after response is sent } else { if ($action == 'nop') { // no action } else { $error = 'action ' . $action . ' not understood by server'; } } } } } } } } } } } } } } $resp = array(); if (isset($error)) { $resp['error'] = $error; console("<*> " + $error); } if (isset($action)) { $resp['action'] = $action; } if (isset($ans)) { $resp['ans'] = $ans; } if (isset($res)) { $resp['res'] = $res; } if (isset($asset)) { $resp['asset'] = $asset; } if (isset($clients)) { $resp['clients'] = $clients; } $resp = json_encode($resp); websocket_send($websocket, $client, $resp); }
/** * @inheritdoc */ public function escapeField($names) { if (!is_resource($this->resource)) { $this->connect(); } $separator = '.'; $r = ''; foreach (explode('.', $names) as $value) { $r .= $separator . pg_escape_identifier($this->resource, $value); } return substr($r, strlen($separator)); }
function escape_identifier($str) { return pg_escape_identifier($this->db, $str); }
protected function getSchema() { $schema = 'public'; $tables = array(); // table_name -> reDBTable $views = array(); // view_name -> reDBView $columns = array(); // table_name -> array( column_name->reDBColumn, column_name->reDBColumn, .. ) $all_columns = array(); // i -> reDBColumn $primary_keys = array(); // table_name -> reDBPrimaryKey $foreign_keys = array(); // table_name -> array( constraint_name->reDBForeignKey, constraint_name->reDBForeignKey, .. ) $all_foreign_keys = array(); // constraint_name -> reDBForeignKey // get tables foreach ($this->queryAssoc('SELECT table_name,table_type FROM information_schema.tables WHERE table_schema=? ORDER BY table_type,table_name', $schema) as $table_def) { $table_name = $table_def['table_name']; $table_escaped_name = pg_escape_identifier($this->conn, $table_name); switch ($table_def['table_type']) { case 'VIEW': $tables[$table_name] = new reDBView($this, $table_name, $table_escaped_name); break; case 'BASE TABLE': $tables[$table_name] = new reDBTable($this, $table_name, $table_escaped_name); break; } } // get columns foreach ($this->queryAssoc('SELECT column_name,ordinal_position,table_name,data_type FROM information_schema.columns WHERE table_schema=? ORDER BY table_name,ordinal_position', $schema) as $def) { $column_name = $def['column_name']; $column_index = intval($def['ordinal_position'], 10) - 1; $column_table_name = $def['table_name']; $column_escaped_name = pg_escape_identifier($this->conn, $column_name); $column = new reDBColumn($tables[$column_table_name], $column_name, $column_escaped_name, $column_index, $def['data_type']); $all_columns[] = $column; $columns[$column_table_name][$column_name] = $column; } // get primary key constraints $tmp_primary_keys = array(); // constraint_name -> array( 'table'=>reDBTable, 'column_names'=>array( column_name, column_name, .. ) ) $rows = $this->queryAssoc('SELECT tc.constraint_name,tc.table_name,kcu.column_name FROM information_schema.table_constraints tc LEFT JOIN information_schema.key_column_usage kcu ON tc.constraint_catalog=kcu.constraint_catalog AND tc.constraint_schema=kcu.constraint_schema AND tc.constraint_name=kcu.constraint_name LEFT JOIN information_schema.referential_constraints rc ON tc.constraint_catalog=rc.constraint_catalog AND tc.constraint_schema=rc.constraint_schema AND tc.constraint_name=rc.constraint_name WHERE tc.table_schema=? AND tc.constraint_type=\'PRIMARY KEY\' ORDER BY tc.constraint_name, kcu.ordinal_position', $schema); foreach ($rows as $row) { $constraint_name = $row['constraint_name']; if (!isset($tmp_primary_keys[$constraint_name])) { $tmp_primary_keys[$constraint_name] = array('table_name' => $row['table_name'], 'column_names' => array()); } $tmp_primary_keys[$constraint_name]['column_names'][] = $row['column_name']; } // create primary keys objects foreach ($tmp_primary_keys as $constraint_name => $pk_tmp) { $table_name = $pk_tmp['table_name']; $primary_keys[$table_name] = new reDBPrimaryKey($tables[$table_name], $constraint_name, $pk_tmp['column_names']); } // get foreign key constraints $tmp_foreign_keys = array(); // constraint_name -> array( 'table'=>reDBTable, 'column_references'=>array( column_name=>references_column_name, column_name=>references_column_name, .. ) ) $rows = $this->queryAssoc('SELECT tc.constraint_name AS constraint_name, kcu1.table_name AS from_table_name, kcu1.column_name AS from_column_name, kcu2.table_name AS to_table_name, kcu2.column_name AS to_column_name FROM information_schema.table_constraints tc LEFT JOIN information_schema.referential_constraints rc ON tc.constraint_catalog=rc.constraint_catalog AND tc.constraint_schema=rc.constraint_schema AND tc.constraint_name=rc.constraint_name LEFT JOIN information_schema.key_column_usage kcu1 ON tc.constraint_catalog=kcu1.constraint_catalog AND tc.constraint_schema=kcu1.constraint_schema AND tc.constraint_name=kcu1.constraint_name LEFT JOIN information_schema.key_column_usage kcu2 ON tc.constraint_catalog=kcu2.constraint_catalog AND tc.constraint_schema=kcu2.constraint_schema AND kcu2.constraint_name=rc.unique_constraint_name AND kcu2.ordinal_position=kcu1.ordinal_position WHERE tc.table_schema=? AND tc.constraint_type=\'FOREIGN KEY\' ORDER BY tc.constraint_name, kcu1.ordinal_position', $schema); foreach ($rows as $row) { $constraint_name = $row['constraint_name']; if (!isset($tmp_foreign_keys[$constraint_name])) { $tmp_foreign_keys[$constraint_name] = array('table_name' => $row['from_table_name'], 'references_table' => $row['to_table_name'], 'column_references' => array()); } $tmp_foreign_keys[$constraint_name]['column_references'][$row['from_column_name']] = $row['to_column_name']; } // create foreign key objects foreach ($tmp_foreign_keys as $constraint_name => $fk_tmp) { $table_name = $fk_tmp['table_name']; $foreign_key = new reDBForeignKey($tables[$table_name], $constraint_name, $tables[$fk_tmp['references_table']], $fk_tmp['column_references']); $foreign_keys[$table_name][$constraint_name] = $foreign_key; $all_foreign_keys[$constraint_name] = $foreign_key; } // initialize tables -> assign them their columns and constraints foreach ($tables as $table_name => $table) { $table_columns = isset($columns[$table_name]) ? $columns[$table_name] : array(); if ($table->isView()) { $table->initialize($table_columns); } else { $table->initialize($table_columns, isset($primary_keys[$table_name]) ? $primary_keys[$table_name] : null, isset($foreign_keys[$table_name]) ? $foreign_keys[$table_name] : array()); } } // return the model return array($tables, $all_foreign_keys); }
public function min($table, $field, $criteria = []) { $field = pg_escape_identifier($field); $query = "select min({$field}) from \"{$table}\""; if (empty($criteria)) { $result = $this->selectCell($query); } else { $query .= $this->getWhere($criteria); $whereParams = $this->getWhereParams($criteria); array_unshift($whereParams, $query); $result = call_user_func_array([$this, 'selectCell'], $whereParams); } return $result; }
/** * * @param string $string * @param int $parameter_type * @return string */ public function quote($string, $parameter_type = AttoDbo_IConnection::PARAM_STR) { if ($parameter_type === AttoDbo_IConnection::PARAM_NULL) { return 'NULL'; } $upper = trim(strtoupper($string)); if ($parameter_type === AttoDbo_IConnection::PARAM_BOOL && ($upper == 'TRUE' || $upper == 'FALSE')) { return $upper; } if ($parameter_type !== AttoDbo_IConnection::PARAM_STR && (is_int($string) || is_numeric($string))) { return $upper; } return pg_escape_identifier($string, $this->_con); }
/** * Escape string[] values * @param array $array * @return string */ public function arrstr(array $array) { $array = array_map(function ($value) { return pg_escape_identifier((string) $value); }, $array); return $this->str(sprintf('{%s}', implode(',', $array))); }
public function convertIdentifierToSql($value) { $parts = explode('.', $value); foreach ($parts as &$part) { if ($part !== '*') { $part = pg_escape_identifier($this->connection, $part); } } return implode('.', $parts); }
} $query .= " LIMIT " . $num_rows . " OFFSET " . $num_rows * $page; $result = pg_query($link, $query); $results_array = array(); if (!$result) { die('Failed to get results ' . pg_last_error()); } if (pg_num_rows($result) > 0) { while ($row = pg_fetch_assoc($result)) { $row_array = array(); foreach ($row as $key => $value) { $row_array[] = $value; } $results_array[] = $row_array; } } $query = "SELECT COUNT(*) FROM " . pg_escape_identifier($_REQUEST["table"]); $result_count = pg_query($link, $query); $row_count = pg_fetch_array($result_count); $num = $row_count[0]; class returnObj { public $rows; public $fields; public $total_entries; } $return_obj = new returnObj(); $return_obj->rows = $results_array; $return_obj->fields = $r_fields; $return_obj->total_entries = $num; echo json_encode($return_obj);
/** * Удаление * @param $table * @param $column * @param int $id * @return void */ public function delete($table, $column, $id) { $this->query("DELETE FROM " . pg_escape_identifier($table) . " WHERE " . $this->escape_identifier($column) . " = " . pg_escape_literal($id) . ";"); }
/** * escapeIdentifier * * Escape database object's names. This is different from value escaping * as objects names are surrounded by double quotes. API function does * provide a nice escaping with -- hopefully -- UTF8 support. * * @see http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html * @access public * @param string $string The string to be escaped. * @return string the escaped string. */ public function escapeIdentifier($string) { return \pg_escape_identifier($this->getHandler(), $string); }
/** * Escape an identifier to be compliant and Safe (against SQL Injection) with PgSQL standards. * This function WILL ADD the DOUBLE QUOTES (") arround the identifiers (fields / table names) as needed. * * @param STRING $y_identifier :: The Identifier to be Escaped: field / table * @param RESOURCE $y_connection :: the connection * @return STRING :: The Escaped Identifier as: "field" / "table" * */ public static function escape_identifier($y_identifier, $y_connection = 'DEFAULT') { //== $y_connection = self::check_connection($y_connection, 'ESCAPE-IDENTIFIER'); //== //-- Fix $y_identifier = (string) SmartUnicode::utf8_to_iso((string) $y_identifier); // this is in sync with validate table and field names to make them all ISO $y_identifier = (string) SmartUnicode::fix_charset((string) $y_identifier); // fix in the case that something went wrong $y_identifier = (string) str_replace('?', '', (string) $y_identifier); // remove ? after conversion //-- //-- $y_identifier = (string) @pg_escape_identifier($y_connection, (string) $y_identifier); // [CONN] //-- //-- return (string) $y_identifier; //-- }