YaWK  24.1
Yet another WebKit
YAWK\db Class Reference

Mysqli database class; returns db connection object. More...

Public Member Functions

 __construct ()
 
 beginTransaction ()
 
 clearResults ()
 
 close ()
 
 commit ()
 
 connect ()
 Connect to the database. More...
 
 deleteDatabase ($database)
 Delete a whole database (including all tables) More...
 
 dropTables ($tables)
 Drop table from a database. More...
 
 error ()
 Fetch last error from the database. More...
 
 get_tables ()
 Get all tables from a database and return as array. More...
 
 import ($sqlfile, $lang)
 Import data from .sql file into database. More...
 
 more_results ()
 Checks if there are more query results from a multi query. More...
 
 multi_query ($query)
 
 next_result ()
 Move to next result set of a multi query. More...
 
 prepare ($sql)
 
 query ($query)
 Execute any sql query. More...
 
 quote ($value)
 Quote and escape value for use in a database query *. More...
 
 real_escape_string ($migrationSql)
 
 rollback ()
 
 select ($query)
 Fetch rows from database (SELECT query) More...
 
 truncateTable (string $table)
 Truncate a table. More...
 

Public Attributes

 $config
 
 $connection
 

Detailed Description

Mysqli database class; returns db connection object.

Database class - connect to mysqli and return connection object

This class establish the database connection if none already exists. It serves some handy methods as well, like quote data, get and delete tables, import .sql files, as well as typical select and query methods.

Author
Daniel Retzl danie.nosp@m.lret.nosp@m.zl@gm.nosp@m.ail..nosp@m.com
Version
1.0.0

Definition at line 16 of file db.php.

Constructor & Destructor Documentation

◆ __construct()

YAWK\db::__construct ( )

db constructor - Include the database config file

Definition at line 26 of file db.php.

28  { // include config array
29  $fullPathToConfigFile = __dir__.'/dbconfig.php';
30  if (!is_file($fullPathToConfigFile))
31  { // db config file not found.
32  die('The Database configuration file is missing. It has been created during the installation process, but it is not reachable.');
33  }
34  else
35  { // include config file
36  require_once ($fullPathToConfigFile);
37  }
die
Definition: block-user.php:27

References die.

Member Function Documentation

◆ beginTransaction()

YAWK\db::beginTransaction ( )
Exceptions
Exception

Definition at line 82 of file db.php.

83  : void
84  {
85  $this->connection->begin_transaction();

◆ clearResults()

YAWK\db::clearResults ( )

Clear all pending result sets after a multi-query

Returns
bool true if successful, false otherwise

Definition at line 179 of file db.php.

181  {
182  try
183  {
184  // Check if there are more result sets available
185  while ($this->connection->more_results() && $this->connection->next_result())
186  {
187  // Store the current result set
188  $result = $this->connection->store_result();
189 
190  // Free the current result set
191  if ($result !== false)
192  {
193  $result->free();
194  }
195  }
196 
197  return true;
198  }
199  catch (\Exception $e)
200  {
201  error_log("Error clearing result sets: " . $e->getMessage());
202  return false;
203  }
$result
Definition: email-send.php:137

References $result.

◆ close()

YAWK\db::close ( )

Definition at line 74 of file db.php.

75  : void
76  {
77  $this->connection->close();

◆ commit()

YAWK\db::commit ( )

Definition at line 97 of file db.php.

98  : void
99  { // commit transaction
100  $this->connection->commit();

◆ connect()

YAWK\db::connect ( )

Connect to the database.

Returns
object|bool false on failure / mysqli MySQLi object instance on success
Exceptions
Exception

Definition at line 44 of file db.php.

45  : object|bool
46  {
47  // if connection is not set
48  if (!isset($this->connection))
49  {
50  try {
51  // create new database object
52  $this->connection = new \mysqli(
53  $this->config['server'],
54  $this->config['username'],
55  $this->config['password'],
56  $this->config['dbname'],
57  $this->config['port']
58  );
59  // connection established successfully
60  return $this->connection;
61  } catch (\mysqli_sql_exception $e) {
62  // failed to connect to database (wrong credentials?)
63  throw new Exception('Failed to connect to database: ' . $e->getMessage());
64  } catch (Exception $e) {
65  throw new Exception('Database connection error: ' . $e->getMessage());
66  }
67  }
68  else
69  {
70  // connection already established...
71  return $this->connection;
72  }
$connection
Definition: db.php:21

References YAWK\db\$connection.

Referenced by YAWK\db\error(), YAWK\db\query(), and YAWK\db\quote().

◆ deleteDatabase()

YAWK\db::deleteDatabase (   $database)

Delete a whole database (including all tables)

Parameters
$database

Definition at line 375 of file db.php.

376  : bool
377  {
378  $deletedTables = 0;
379  $errors = 0;
380 
381  // get all tables as array
382  $result = $this->query("SHOW TABLES IN `$database`");
383  // check if result is set
384 
385  if (isset($result) && (!empty($result)))
386  {
387  // walk through result array
388  while ($table = mysqli_fetch_array($result))
389  { // store tablename in var
390  $tableName = $table[0];
391  // try to delete table
392  if ($this->query("DROP TABLE `$database`.`$tableName`"))
393  { // output(?)
394  //echo "$tableName was cleared <br>";
395  $deletedTables++;
396  }
397  else
398  { // output error
399  $errors++;
400  }
401  }
402  }
403  // something went wrong
404  if ($errors > 0)
405  { // output error
406  return false;
407  }
408  else {
409  return true;
410  }
query($query)
Execute any sql query.
Definition: db.php:213

◆ dropTables()

YAWK\db::dropTables (   $tables)

Drop table from a database.

Parameters
array$tablesthe tables to drop
Returns
bool

Definition at line 457 of file db.php.

459  {
460  $processed = 0;
461  // check if table was set
462  if (!isset($tables) || (empty($tables)) || (!array($tables)))
463  {
464  return false;
465  }
466  foreach ($tables as $table)
467  {
468  if ($this->query("DROP TABLE `".$table."`") === true)
469  {
470  $processed++;
471  }
472  }
473  return true;

◆ error()

YAWK\db::error ( )

Fetch last error from the database.

Returns
string database error

Definition at line 273 of file db.php.

275  {
276  // connect to database
277  $this->connection = $this->connect();
278  // return latest error
279  return $this->connection->error;
connect()
Connect to the database.
Definition: db.php:44

References YAWK\db\connect().

◆ get_tables()

YAWK\db::get_tables ( )

Get all tables from a database and return as array.

Returns
array tableList

Definition at line 416 of file db.php.

418  {
419  // set tableList array
420  $tableList = array();
421  // get tables from database
422  $res = $this->query("SHOW TABLES");
423  // walk through result
424  while($row = mysqli_fetch_array($res))
425  { // fill array
426  $tableList[] = $row[0];
427  }
428  return $tableList;

◆ import()

YAWK\db::import (   $sqlfile,
  $lang 
)

Import data from .sql file into database.

Parameters
$sqlfile
$lang
Returns
bool

Definition at line 300 of file db.php.

302  {
303  // http://stackoverflow.com/questions/19751354/how-to-import-sql-file-in-mysql-database-using-php
304  if (!isset($sqlfile) || (empty($sqlfile)))
305  {
306  $filename = 'yawk_database.sql';
307  }
308  else
309  {
310  $filename = $sqlfile;
311  }
312  // filename
313  // $maxRuntime = 8; // less then your max script execution limit
314  // $maxRuntime = 8; // less then your max script execution limit
315 
316  // $deadline = time()+$maxRuntime;
317  $progressFilename = $filename.'_filepointer'; // tmp file for progress
318  $errorFilename = $filename.'_error'; // tmp file for erro
319 
320  ($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);
321 
322  // check for previous error
323  if(file_exists($errorFilename) )
324  {
325  // die('<pre> previous error: '.file_get_contents($errorFilename));
326  }
327 
328  // go to previous file position
329  $filePosition = 0;
330  if(file_exists($progressFilename))
331  {
332  $filePosition = file_get_contents($progressFilename);
333  fseek($fp, $filePosition);
334  }
335 
336  $queryCount = 0;
337  $query = '';
338  while($line=fgets($fp, 1024000))
339  {
340  if(substr($line,0,2)=='--' OR trim($line)=='' )
341  {
342  continue;
343  }
344 
345  $query .= $line;
346  if( substr(trim($query),-1)==';' )
347  {
348  if(!$this->query($query))
349  { // error handling
350  $error = 'Error performing query \'<strong>' . $query . '\': ' . @mysqli_error($this);
351  @file_put_contents($errorFilename, $error."\n");
352  //exit;
353  }
354  $query = '';
355  @file_put_contents($progressFilename, ftell($fp)); // save the current file position for
356  $queryCount++;
357  }
358  }
359 
360  if(feof($fp))
361  {
362  return true;
363  }
364  else
365  {
366  // $status .= ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
367  return false;
368  }
$filename
Definition: actions.php:10

References $error, $filename, die, and YAWK\db\query().

◆ more_results()

YAWK\db::more_results ( )

Checks if there are more query results from a multi query.

Returns
bool

Definition at line 162 of file db.php.

163  : bool
164  {
165  if (method_exists($this->connection, 'more_results'))
166  {
167 // sys::setSyslog($this->connection, 53, 0, "more migration results available", 0, 0, 0, 0);
168  return $this->connection->more_results() && $this->connection->next_result() && $this->connection->store_result();
169  }
170  else
171  {
172  return false;
173  }

Referenced by YAWK\db\next_result().

◆ multi_query()

YAWK\db::multi_query (   $query)

Definition at line 87 of file db.php.

89  { // query database
90  return $this->connection->multi_query($query);

◆ next_result()

YAWK\db::next_result ( )

Move to next result set of a multi query.

Returns
bool

Definition at line 141 of file db.php.

143  {
144  if (method_exists($this->connection, 'next_result'))
145  {
146 // sys::setSyslog($this->connection, 53, 0, "next result called", 0, 0, 0, 0);
147  return $this->connection->next_result();
148  }
149  else
150  {
151  // Free any active result sets
152  while ($this->more_results() && $this->connection->next_result()) {
153 // sys::setSyslog($this->connection, 53, 0, "free any active result sets", 0, 0, 0, 0);
154  }
155  return true;
156  }
more_results()
Checks if there are more query results from a multi query.
Definition: db.php:162

References YAWK\db\more_results().

◆ prepare()

YAWK\db::prepare (   $sql)

Definition at line 92 of file db.php.

94  { // prepare statement
95  return $this->connection->prepare($sql);
$sql
Definition: message-new.php:32

References $sql.

◆ query()

YAWK\db::query (   $query)

Execute any sql query.

Parameters
string$querythe sql query string
Returns
mixed The mysqli result

Definition at line 213 of file db.php.

215  {
216  // connect to database
217  if ($this->connection = $this->connect())
218  {
219  // if connection is successful
220 
221  // replace {} in str to add table prefix
222  $query = str_replace("}", "", $query);
223  $query = str_replace("{", $this->config['prefix'], $query);
224 
225  // query database
226  return $this->connection->query($query);
227  }
228  else
229  { // could not connect to database, exit with error
230  die ('Database error: '.mysqli_connect_error().'('.mysqli_connect_errno().')');
231  }

References YAWK\db\connect(), and die.

Referenced by YAWK\db\import(), and YAWK\db\select().

◆ quote()

YAWK\db::quote (   $value)

Quote and escape value for use in a database query *.

Parameters
string$valuethe value to be quoted and escaped
Returns
string the quoted and escaped string

Definition at line 286 of file db.php.

288  {
289  // connect to database
290  $this->connection = $this->connect();
291  // escape and return string
292  return $this->connection->real_escape_string($value);
$value

References $value, and YAWK\db\connect().

◆ real_escape_string()

YAWK\db::real_escape_string (   $migrationSql)

Definition at line 102 of file db.php.

103  {
104  return $this->connection->real_escape_string($migrationSql);

◆ rollback()

YAWK\db::rollback ( )

Rollback the current transaction

Returns
bool true if rollback succeeded, false otherwise

Definition at line 111 of file db.php.

113  {
114  try
115  {
116  while ($this->connection->more_results())
117  {
118  $this->connection->next_result();
119  }
120 
121  // Rollback the transaction
122  $result = $this->connection->rollback();
123 
124  if ($result)
125  { // Rollback succeeded
126  return true;
127  }
128 
129  }
130  catch (\Exception $e)
131  {
132  // An exception was thrown, so rollback failed
133  return false;
134  }
135  return false;

References $result.

◆ select()

YAWK\db::select (   $query)

Fetch rows from database (SELECT query)

Parameters
string$querythe sql query string
Returns
array|bool on failure

Definition at line 238 of file db.php.

240  {
241  // init result rows array
242  $rows = array();
243  // query database
244  $result = $this->query($query);
245  // check if result is false
246  if ($result === false)
247  {
248  // $error = $this->error();
249  //\YAWK\sys::setSyslog($db, 5, "$error", 0, 0, 0, 0);
250  return false;
251  }
252  else
253  { // fetch associative result
254  while ($row = $result->fetch_assoc())
255  { // fill array
256  $rows[] = $row;
257  }
258  }
259  // check if result rows array is set
260  if (isset($rows) && (!empty($rows) && (is_array($rows))))
261  { // ok, return result rows
262  return $rows;
263  }
264  else
265  { // no result set
266  return false;
267  }
$rows
Definition: menus.php:126

References $result, $rows, and YAWK\db\query().

◆ truncateTable()

YAWK\db::truncateTable ( string  $table)

Truncate a table.

Parameters
$tablestring the table to truncate
Returns
bool

Definition at line 435 of file db.php.

436  : bool
437  {
438  if (!empty($table))
439  {
440  $table = '{'.$table.'}';
441  if ($this->query("TRUNCATE TABLE $table"))
442  { // success
443  return true;
444  }
445  else
446  { // error
447  return false;
448  }
449  }
450  return false;

Member Data Documentation

◆ $config

YAWK\db::$config
Parameters
array$configmysql configuration (host, username, database etc...)

Definition at line 19 of file db.php.

◆ $connection

YAWK\db::$connection
Parameters
object$connectionholds the mysqli database connection

Definition at line 21 of file db.php.

Referenced by YAWK\db\connect().


The documentation for this class was generated from the following file: