Exemplo n.º 1
0
 /**
  * Execute a raw SQL query.
  *
  * @param string $sql The SQL to execute.
  * @param array $params Parameters used in the SQL.
  */
 public function query($sql, array $params = array())
 {
     $querytype = mb_strtoupper(mb_substr($sql, 0, 6));
     // Ensure UTF-8.
     foreach ($params as $k => $v) {
         $params[$k] = \pdyn\datatype\Text::force_utf8($v);
     }
     // Prefix tables.
     $sql = preg_replace_callback('#\\{(.+)\\}#msU', function ($matches) {
         return $this->transform_tablename($matches[1]);
     }, $sql);
     // Logging.
     $this->log($sql, $params);
     if (!is_array($params)) {
         throw new \Exception('Bad params argument in $DB->query', static::ERR_DB_BAD_REQUEST);
     }
     if (empty($this->link)) {
         throw new \Exception('No database connection present.', static::ERR_DB_BAD_REQUEST);
     }
     if (empty($params)) {
         $stmt = $this->link->query($sql);
     } else {
         $stmt = $this->link->prepare($sql, [\PDO::ATTR_CURSOR => \PDO::CURSOR_FWDONLY]);
         if (!empty($stmt)) {
             $stmt->execute($params);
             $errinfo = $stmt->errorInfo();
             if ($errinfo[0] !== '00000') {
                 throw new \Exception($errinfo[2], static::ERR_DB_BAD_REQUEST);
             }
             if (in_array($querytype, ['INSERT', 'UPDATE', 'DELETE'], true)) {
                 $affected_rows = $stmt->rowCount();
             }
         }
     }
     $errinfo = $this->link->errorInfo();
     if ($errinfo[0] !== '00000') {
         throw new \Exception($errinfo[2], static::ERR_DB_BAD_REQUEST);
     }
     $this->numqueries++;
     $this->laststmt = $stmt;
     $lastid = $this->link->lastInsertId();
     $ar = ['affected_rows' => isset($affected_rows) ? $affected_rows : -1, 'last_id' => $querytype === 'INSERT' && !empty($lastid) ? $lastid : 0];
     return $ar;
 }
Exemplo n.º 2
0
 /**
  * Force a value to UTF-8, then serialize.
  *
  * This is used before storing serialized values in the database. Since our DbDrivers convert all strings to UTF-8,
  * they can damage seralized data. For example, if non-utf8 text is contained in a serialized array, the offset recorded in the
  * serialized string may be not reflect the length after conversion to utf8.
  *
  * @param mixed $input A value to force to UTF-8 then serialize.
  * @return string A serialized UTF-8 value.
  */
 public static function utf8safe_serialize($input)
 {
     if (is_array($input)) {
         return serialize(\pdyn\datatype\Text::force_utf8_array($input));
     } elseif (is_string($input)) {
         return serialize(\pdyn\datatype\Text::force_utf8($input));
     } else {
         return serialize($input);
     }
 }