Ignore:
Timestamp:
Jun 1, 2023, 12:18:18 AM (19 months ago)
Author:
chronos
Message:
  • Modified: Updated Common package.
  • Modified: Form types made as separate FormManager package.
  • Fixed: PHP 8.1 support.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/Packages/Common/Database.php

    r7 r8  
    22
    33// Extended database class
    4 // Date: 2016-01-11
     4// Date: 2020-11-10
     5
     6function microtime_float()
     7{
     8  list($usec, $sec) = explode(" ", microtime());
     9  return (float)$usec + (float)$sec;
     10}
    511
    612class DatabaseResult
    713{
    8   var $PDOStatement;
    9   var $num_rows = 0;
     14  public PDOStatement $PDOStatement;
     15  public int $num_rows = 0;
    1016
    1117  function fetch_assoc()
     
    2733class Database
    2834{
    29   var $Prefix;
    30   var $Functions;
    31   var $Type;
    32   var $PDO;
    33   var $Error;
    34   var $insert_id;
    35   var $LastQuery;
    36   var $ShowSQLError;
    37   var $ShowSQLQuery;
    38   var $LogSQLQuery;
    39   var $LogFile;
     35  public string $Prefix;
     36  public array $Functions;
     37  public string $Type;
     38  public PDO $PDO;
     39  public string $Error;
     40  public string $insert_id;
     41  public string $LastQuery;
     42  public bool $ShowSQLError;
     43  public bool $ShowSQLQuery;
     44  public bool $LogSQLQuery;
     45  public string $LogFile;
     46  public string $Database;
    4047
    4148  function __construct()
    4249  {
    4350    $this->Prefix = '';
    44     $this->Functions = array('NOW()', 'CURDATE()', 'CURTIME()', 'UUID()');
     51    $this->Functions = array('NOW(', 'CURDATE(', 'CURTIME(', 'UUID(', 'SHA1(');
    4552    $this->Type = 'mysql';  // mysql, pgsql
    4653    $this->Error = '';
     
    5057    $this->LogSQLQuery = false;
    5158    $this->LogFile = dirname(__FILE__).'/../../Query.log';
    52   }
    53 
    54   function Connect($Host, $User, $Password, $Database)
     59    $this->Database = '';
     60  }
     61
     62  function Connect(string $Host, string $User, string $Password, string $Database): void
    5563  {
    5664    if ($this->Type == 'mysql') $ConnectionString = 'mysql:host='.$Host.';dbname='.$Database;
    5765      else if ($this->Type == 'pgsql') $ConnectionString = 'pgsql:dbname='.$Database.';host='.$Host;
    5866      else $ConnectionString = '';
     67    $this->Database = $Database;
    5968    try {
    6069      $this->PDO = new PDO($ConnectionString, $User, $Password);
    61 
    6270    } catch (Exception $E)
    6371    {
     
    6775  }
    6876
    69   function Disconnect()
     77  function Disconnect(): void
    7078  {
    7179    unset($this->PDO);
    7280  }
    7381
    74   function Connected()
     82  function Connected(): bool
    7583  {
    7684    return isset($this->PDO);
    7785  }
    7886
    79   function select_db($Database)
     87  function select_db(string $Database)
    8088  {
    8189    $this->query('USE `'.$Database.'`');
    8290  }
    8391
    84   function query($Query)
     92  function query($Query): DatabaseResult
    8593  {
    8694    if (!$this->Connected()) throw new Exception(T('Not connected to database'));
    87     if (($this->ShowSQLQuery == true) or ($this->LogSQLQuery == true)) $QueryStartTime = microtime();
     95    if (($this->ShowSQLQuery == true) or ($this->LogSQLQuery == true)) $QueryStartTime = microtime_float();
    8896    $this->LastQuery = $Query;
    8997    if (($this->ShowSQLQuery == true) or ($this->LogSQLQuery == true))
    90       $Duration = ' ; '.round(microtime() - $QueryStartTime, 4). ' s';
    91     if ($this->LogSQLQuery == true)
     98    {
     99      $Time = round(microtime_float() - $QueryStartTime, 4);
     100      $Duration = ' ; '.$Time. ' s';
     101    }
     102    if (($this->LogSQLQuery == true) and ($Time != 0))
    92103      file_put_contents($this->LogFile, $Query.$Duration."\n", FILE_APPEND);
    93104    if ($this->ShowSQLQuery == true)
     
    95106      'padding-bottom: 3px; padding-top: 3px; font-size: 12px; font-family: Arial;">'.$Query.$Duration.'</div>'."\n");
    96107    $Result = new DatabaseResult();
    97     $Result->PDOStatement = $this->PDO->query($Query);
    98     if ($Result->PDOStatement)
    99     {
    100       $Result->num_rows = $Result->PDOStatement->rowCount();
     108    $Statement = $this->PDO->query($Query);
     109    if ($Statement)
     110    {
     111      $Result->PDOStatement = $Statement;
     112      $Result->num_rows = $Statement->rowCount();
    101113      $this->insert_id = $this->PDO->lastInsertId();
    102114    } else
    103115    {
    104       $this->Error = $this->PDO->errorInfo();
    105       $this->Error = $this->Error[2];
     116      $Error = $this->PDO->errorInfo();
     117      $this->Error = $Error[2];
    106118      if (($this->Error != '') and ($this->ShowSQLError == true))
    107119        echo('<div><strong>SQL Error: </strong>'.$this->Error.'<br />'.$Query.'</div>');
     
    111123  }
    112124
    113   function select($Table, $What = '*', $Condition = 1)
     125  function select(string $Table, string $What = '*', string $Condition = '1'): DatabaseResult
    114126  {
    115127    return $this->query('SELECT '.$What.' FROM `'.$this->Prefix.$Table.'` WHERE '.$Condition);
    116128  }
    117129
    118   function delete($Table, $Condition)
     130  function delete(string $Table, string $Condition): void
    119131  {
    120132    $this->query('DELETE FROM `'.$this->Prefix.$Table.'` WHERE '.$Condition);
    121133  }
    122134
    123   function insert($Table, $Data)
     135  function insert(string $Table, array $Data): int
     136  {
     137    $this->query($this->GetInsert($Table, $Data));
     138    $this->insert_id = $this->PDO->lastInsertId();
     139    return $this->insert_id;
     140  }
     141
     142  function IsFunction(string $Text): bool
     143  {
     144    $Pos = strpos($Text, '(');
     145    return ($Pos !== false) && in_array(substr($Text, 0, $Pos + 1), $this->Functions);
     146  }
     147
     148  function GetInsert(string $Table, array $Data): string
    124149  {
    125150    $Name = '';
     
    128153    {
    129154      $Name .= ',`'.$Key.'`';
    130       if (!in_array($Value, $this->Functions))
     155      if (is_null($Value)) $Value = 'NULL';
     156      else if (!$this->IsFunction($Value))
    131157      {
    132         if (is_null($Value)) $Value = 'NULL';
    133         else $Value = $this->PDO->quote($Value);
     158        $Value = $this->PDO->quote($Value);
    134159      }
    135160      $Values .= ','.$Value;
     
    137162    $Name = substr($Name, 1);
    138163    $Values = substr($Values, 1);
    139     $this->query('INSERT INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES('.$Values.')');
    140     $this->insert_id = $this->PDO->lastInsertId();
    141   }
    142 
    143   function update($Table, $Condition, $Data)
     164    return 'INSERT INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES('.$Values.')';
     165  }
     166
     167  function update(string $Table, string $Condition, array $Data): void
     168  {
     169    $this->query($this->GetUpdate($Table, $Condition, $Data));
     170  }
     171
     172  function GetUpdate(string $Table, string $Condition, array $Data): string
    144173  {
    145174    $Values = '';
    146175    foreach ($Data as $Key => $Value)
    147176    {
    148       if (!in_array($Value, $this->Functions))
     177      if (is_null($Value)) $Value = 'NULL';
     178      else if (!$this->IsFunction($Value))
    149179      {
    150         if (is_null($Value)) $Value = 'NULL';
    151         else $Value = $this->PDO->quote($Value);
     180        $Value = $this->PDO->quote($Value);
    152181      }
    153182      $Values .= ', `'.$Key.'`='.$Value;
    154183    }
    155184    $Values = substr($Values, 2);
    156     $this->query('UPDATE `'.$this->Prefix.$Table.'` SET '.$Values.' WHERE ('.$Condition.')');
    157   }
    158 
    159   function replace($Table, $Data)
     185    return 'UPDATE `'.$this->Prefix.$Table.'` SET '.$Values.' WHERE ('.$Condition.')';
     186  }
     187
     188  function replace(string $Table, array $Data): void
    160189  {
    161190    $Name = '';
     
    163192    foreach ($Data as $Key => $Value)
    164193    {
    165       if (!in_array($Value, $this->Functions))
     194      if (is_null($Value)) $Value = 'NULL';
     195      else if (!$this->IsFunction($Value))
    166196      {
    167         if (is_null($Value)) $Value = 'NULL';
    168         else $Value = $this->PDO->quote($Value);
     197        $Value = $this->PDO->quote($Value);
    169198      }
    170199      $Name .= ',`'.$Key.'`';
     
    173202    $Name = substr($Name, 1);
    174203    $Values = substr($Values, 1);
    175     //echo('REPLACE INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES ('.$Values.')<br />');
    176204    $this->query('REPLACE INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES('.$Values.')');
    177     //echo($this->error().'<br>');
    178   }
    179 
    180   function charset($Charset)
     205  }
     206
     207  function charset(string $Charset): void
    181208  {
    182209    $this->query('SET NAMES "'.$Charset.'"');
    183210  }
    184211
    185   function real_escape_string($Text)
     212  function real_escape_string(string $Text): string
    186213  {
    187214    return addslashes($Text);
    188215  }
    189216
    190   function quote($Text)
     217  function quote(string $Text): string
    191218  {
    192219    return $this->PDO->quote($Text);
    193220  }
    194221
    195   public function __sleep()
     222  public function __sleep(): array
    196223  {
    197224    return array('LastQuery');
    198225  }
    199226
    200   public function __wakeup()
    201   {
     227  public function __wakeup(): void
     228  {
     229  }
     230
     231  public function Transaction(array $Queries): void
     232  {
     233    $this->PDO->beginTransaction();
     234    foreach ($Queries as $Query)
     235    {
     236      $Statement = $this->PDO->prepare($Query);
     237      $Statement->execute();
     238    }
     239    $this->PDO->commit();
     240  }
     241
     242  public function TableExists(string $Name): bool
     243  {
     244    $DbResult = $this->query('SELECT * FROM information_schema.tables  WHERE table_schema = "'.$this->Database.
     245    '" AND table_name = "'.$Name.'" LIMIT 1');
     246    return $DbResult->num_rows != 0;
    202247  }
    203248}
Note: See TracChangeset for help on using the changeset viewer.