This page lists files in the current directory. You can view content, get download/execute commands for Wget, Curl, or PowerShell, or filter the list using wildcards (e.g., `*.sh`).
wget 'https://sme10.lists2.roe3.org/pmnl3/include/db/PDOExtended/LICENSE'
The MIT License (MIT)
Copyright (c) 2013 bengates
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
wget 'https://sme10.lists2.roe3.org/pmnl3/include/db/PDOExtended/PDOExtended.php'
<?php
/**
* MIT License (MIT)
*
* Copyright (c) 2013 Beno!t POLASZEK
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* PDOExtended class
* @author Beno!t POLASZEK - 2013
*/
require_once __DIR__ . '/PDOStatementExtended.php';
require_once __DIR__ . '/StmtException.php';
Class PDOExtended {
protected $PDO;
protected $Dsn;
protected $Username;
protected $Password;
protected $DriversOptions;
protected $IsConnected = false;
protected $IsPaused = false;
const TO_ARRAY_ASSOC = 1;
const TO_ARRAY_INDEX = 2;
const TO_STRING = 3;
const TO_STDCLASS = 4;
/**
* Constructor
* @link http://php.net/manual/en/pdo.construct.php
* @access public
* @author Beno!t POLASZEK - 2013
*/
public function __construct() {
# Catching constructor arguments
$Args = func_get_args();
# Setting properties
$this -> Dsn = (array_key_exists(0, $Args)) ? $Args[0] : null;
$this -> Username = (array_key_exists(1, $Args)) ? $Args[1] : null;
$this -> Password = (array_key_exists(2, $Args)) ? $Args[2] : null;
$this -> DriversOptions = (array_key_exists(3, $Args)) ? $Args[3] : null;
# Creating PDO instance into $this->PDO
$Class = new \ReflectionClass('\PDO');
$this -> PDO = $Class->NewInstanceArgs($Args);
$this -> PDO -> SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this -> PDO -> SetAttribute(PDO::ATTR_STATEMENT_CLASS, Array(__NAMESPACE__ . '\PDOStatementExtended'));
# Checking PDO connection
$this -> IsConnected = $this->Ping();
$this -> IsPaused = false;
}
/**
* Constructor alias - useful for chaining
* Example : $Status = PDOExtended::NewInstance('mysql:host=localhost', 'user', 'password')->SqlMultiAssoc("SHOW GLOBAL STATUS");
*/
public static function NewInstance() {
$CurrentClass = new \ReflectionClass(get_called_class());
return $CurrentClass->NewInstanceArgs(func_get_args());
}
/**
* Destructor : disconnection
*/
public function __destruct() {
$this->Disconnect();
}
/**
* Magic Shortcut to PDO object methods
* @access public
* @author Beno!t POLASZEK - 2013
*/
public function __call($Name, array $Args) {
# If the connection was paused, we have to reconnect
!$this->IsPaused OR $this->Reconnect();
if (!($this->PDO instanceof \PDO))
throw new \PDOException("PDO Connection isn't active.");
return call_user_func_array(array($this->PDO, $Name), $Args);
}
/**
* Checks if connection is active
*
* @return bool true / false
* @access public
* @author Beno!t POLASZEK - 2013
*/
public function Ping() {
if ($this->IsPaused)
return false;
try {
return (bool) $this->Query("SELECT 1+1");
}
catch (Exception $e) {
return false;
}
}
/**
* Closes the current connection
* Next calls (query, prepare, etc) will throw an exception unless you use Reconnect() method
*
* @return PDOExtended instance
* @access public
* @author Beno!t POLASZEK - 2013
*/
public function Disconnect() {
$this -> PDO = null;
$this -> IsConnected = false;
return $this;
}
/**
* Pauses the current connection (disconnects temporarily)
* The connexion will be closed but reopened at the next call (query, prepare, sql etc)
*
* @return PDOExtended instance
* @access public
* @author Beno!t POLASZEK - 2013
*/
public function Pause() {
$this -> Disconnect();
$this -> IsPaused = true;
return $this;
}
/**
* Re-opens the connection with the same dsn / username / passwd etc
*
* @return PDOExtended instance
* @access public
* @author Beno!t POLASZEK - 2013
*/
public function Reconnect() {
self::__construct($this->Dsn, $this->Username, $this->Password, $this->DriversOptions);
return $this;
}
/**
* Prepares a SQL Statement
*
* @param string SqlString : SQL query
* @param array $SqlValues : Optional PDO Values to bind
* @param array $DriversOptions
* @return PDOStatementExtended Stmt
* @access public
* @author Beno!t POLASZEK - 2013
*/
public function Prepare($SqlString, $SqlValues = array(), $DriversOptions = array()) {
# If the connection was paused, we have to reconnect
!$this->IsPaused OR $this->Reconnect();
if (!($this->PDO instanceof \PDO))
throw new \PDOException("PDO Connection isn't active.");
# The SQL Query becomes a SQL Statement
$Stmt = $this->PDO->Prepare($SqlString, $DriversOptions);
if (empty($SqlValues))
return $Stmt;
# If values have been provided, let's bind them
else
$Stmt->BindValues($SqlValues);
return $Stmt;
}
/**
* Prepares a SQL Statement and executes it
*
* @param mixed $SqlString : SQL Query (String or instanceof PDOStatement)
* @param array $SqlValues : Optional PDO Values to bind
* @param array $DriversOptions
* @return PDOStatementExtended Stmt (executed)
* @access public
*/
public function Sql($SqlString, $SqlValues = array(), $DriversOptions = array()) {
# If the connection was paused, we have to reconnect
!$this->IsPaused OR $this->Reconnect();
if (!($this->PDO instanceof \PDO))
throw new \PDOException("PDO Connection isn't active.");
# If SqlString isn't a PDOStatement yet
$Stmt = ($SqlString instanceof PDOStatement) ? $SqlString : $this->Prepare($SqlString, $SqlValues, $DriversOptions);
# If values have been provided, let's bind them
if (!empty($SqlValues))
$Stmt->BindValues($SqlValues);
# Execution
try {
$Stmt->Execute();
}
# Custom PDO Exception, allowing query preview
catch (PDOException $PDOException) {
throw new StmtException((string) $PDOException->GetMessage(), $PDOException->GetCode(), $PDOException, $Stmt->Debug());
}
# The statement is executed. You can now use Fetch() and FetchAll() methods.
return $Stmt;
}
/**
* SqlArray executes Query : returns the whole result set
*
* @param mixed $SqlString : SQL Query (String or instanceof PDOStatement)
* @param array $SqlValues : Optional PDO Values to bind
* @return Array
*/
public function SqlArray($SqlString, $SqlValues = array()) {
return $this->Sql($SqlString, $SqlValues)->FetchAll(PDO::FETCH_ASSOC);
}
/**
* SqlRow executes Query : returns the 1st row of your result set
*
* @param mixed $SqlString : SQL Query (String or instanceof PDOStatement)
* @param array $SqlValues : Optional PDO Values to bind
* @return Array
*/
public function SqlRow($SqlString, $SqlValues = array()) {
return $this->Sql($SqlString, $SqlValues)->Fetch(PDO::FETCH_ASSOC);
}
/**
* SqlColumn executes Query : returns the 1st column of your result set
*
* @param mixed $SqlString : SQL Query (String or instanceof PDOStatement)
* @param array $SqlValues : Optional PDO Values to bind
* @return Array
*/
public function SqlColumn($SqlString, $SqlValues = array()) {
return $this->Sql($SqlString, $SqlValues)->FetchAll(PDO::FETCH_COLUMN);
}
/**
* SqlValue executes Query : returns the 1st cell of your result set
*
* @param mixed $SqlString : SQL Query (String or instanceof PDOStatement)
* @param array $SqlValues : Optional PDO Values to bind
* @return String
*/
public function SqlValue($SqlString, $SqlValues = array()) {
return $this->Sql($SqlString, $SqlValues)->Fetch(PDO::FETCH_COLUMN);
}
/**
* SqlAssoc executes Query :
* If $DataType == self::TO_STRING : returns an associative array where the 1st column is the key and the 2nd is the value
* If $DataType == self::TO_STDCLASS : returns an associative array where the 1st column is the key the others are properties of an anonymous object
* If $DataType == self::TO_ARRAY_ASSOC : returns an associative array where the 1st column is the key the others are an associative array
* If $DataType == self::TO_ARRAY_INDEX : returns an associative array where the 1st column is the key the others are an indexed array
*
* @param mixed $SqlString : SQL Query (String or instanceof PDOStatement)
* @param array $SqlValues : PDO Values to bind
* @param int $DataType : type of data wanted
* @return Array
*/
public function SqlAssoc($SqlString, $SqlValues = array(), $DataType = self::TO_STRING) {
$Data = $this->Sql($SqlString, $SqlValues)->Fetch(PDO::FETCH_ASSOC);
if ($Data) :
$Keys = array_keys($Data);
$Result = Array();
if ($DataType == self::TO_STDCLASS)
$Result = Array($Data[$Keys[0]] => (object) array_slice($Data, 1));
elseif ($DataType == self::TO_ARRAY_ASSOC)
$Result = Array($Data[$Keys[0]] => array_slice($Data, 1));
elseif ($DataType == self::TO_ARRAY_INDEX)
$Result = Array($Data[$Keys[0]] => array_values(array_slice($Data, 1)));
else // $DataType == self::TO_STRING by default
$Result = Array($Data[$Keys[0]] => $Data[$Keys[1]]);
return $Result;
else :
return $Data;
endif;
}
/**
* SqlMultiAssoc executes Query :
* If $DataType == self::TO_STRING : returns an associative array where the 1st column is the key and the 2nd is the value
* If $DataType == self::TO_STDCLASS : returns an associative array where the 1st column is the key the others are properties of an anonymous object
* If $DataType == self::TO_ARRAY_ASSOC : returns an associative array where the 1st column is the key the others are an associative array
* If $DataType == self::TO_ARRAY_INDEX : returns an associative array where the 1st column is the key the others are an indexed array
*
* @param mixed $SqlString : SQL Query as a string or a PDOStatementExtended
* @param array $SqlValues : PDO Values to bind
* @param int $DataType : type of data wanted
* @return Array
*/
public function SqlMultiAssoc($SqlString, $SqlValues = array(), $DataType = self::TO_STRING) {
$Data = $this->Sql($SqlString, $SqlValues)->FetchAll(PDO::FETCH_ASSOC);
if (array_key_exists(0, $Data)) :
$Keys = array_keys($Data[0]);
$Result = Array();
foreach ($Data AS $Item)
if ($DataType == self::TO_STDCLASS)
$Result[] = Array($Item[$Keys[0]] => (object) array_slice($Item, 1));
elseif ($DataType == self::TO_ARRAY_ASSOC)
$Result[] = Array($Item[$Keys[0]] => array_slice($Item, 1));
elseif ($DataType == self::TO_ARRAY_INDEX)
$Result[] = Array($Item[$Keys[0]] => array_values(array_slice($Item, 1)));
else // $DataType == self::TO_STRING by default
$Result[] = Array($Item[$Keys[0]] => $Item[$Keys[1]]);
return $Result;
else :
return $Data;
endif;
}
/**
* Prevents from XSS injection
*
* @param mixed $Input
* @return string
* @access public
*/
public static function CleanInput($Input, $ScriptTags = true, $StyleTags = true, $MultiLineComments = true) {
$RemovePatterns = Array();
(bool) $ScriptTags AND $RemovePatterns[] = '@<script[^>]*?>.*?</script>@si'; // Strip out javascript
(bool) $StyleTags AND $RemovePatterns[] = '@<style[^>]*?>.*?</style>@siU'; // Strip style tags properly
(bool) $MultiLineComments AND $RemovePatterns[] = '@<![\s\S]*?--[ \t\n\r]*>@'; // Strip multi-line comments
return preg_replace($RemovePatterns, null, $Input);
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/db/PDOExtended/PDOExtendedSingleton.php'
<?php
/**
* MIT License (MIT)
*
* Copyright (c) 2013 Beno!t POLASZEK
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* PDOExtendedSingleton trait
* @author Beno!t POLASZEK - 2013
*/
require_once __DIR__ . '/PDOExtended.php';
Trait PDOExtendedSingleton {
/**
* Current Instance
*/
private static $instance;
/**
* PDO object Instance
*/
private $PDOInstance = null;
/**
* Constructor
*
* @param string $dsn : Data source name
* @param string $username : User Name
* @param string $password : User Password
* @param string $driver_options : PDO Specific options
* @return PDO PDOInstance
*/
private function __construct($dsn, $username = null, $password = null, $driver_options = null) {
$this->PDOInstance = new PDOExtended($dsn, $username, $password, $driver_options);
}
/**
* Singleton call
*
* @param string $dsn : Data source name
* @param string $username : User Name
* @param string $password : User Password
* @param string $driver_options : PDO Specific options
* @return PDO PDOInstance
*/
public static function Cnx($dsn = null, $username = null, $password = null, $driver_options = null) {
if (is_null(self::$instance))
self::$instance = new self($dsn, $username, $password, $driver_options);
return self::$instance;
}
/**
* Magic call - PDOExtended and PDO methods
*/
public function __call($Method, $Args = null) {
return call_user_func_array(Array($this->PDOInstance, $Method), $Args);
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/db/PDOExtended/PDOStatementExtended.php'
<?php
/**
* MIT License (MIT)
*
* Copyright (c) 2013 Beno!t POLASZEK
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* PDOStatementExtended class
* @author Beno!t POLASZEK - 2013
*/
Class PDOStatementExtended Extends PDOStatement {
protected $Keywords = Array();
protected $BoundValues = Array();
public $queryString;
protected $Preview;
protected $Duration;
protected $Executed = false;
protected $ExecCount = 0;
/**
* When bindValue() is called, we store its params
*/
public function BindValue($Parameter, $Value, $PDOType = null) {
# Flush Bound Values if statement has previously been executed
if ($this->Executed)
$this->BoundValues = Array() AND $this->Executed = false;
$this->BoundValues[] = Array('Parameter' => $Parameter, 'Value' => $Value, 'PDOType' => $PDOType);
parent::BindValue($Parameter, $Value, $PDOType);
return $this;
}
/**
* Binds several values at once
*/
public function BindValues($SqlValues = array()) {
if (empty($SqlValues))
return $this;
if (!is_array($SqlValues))
$SqlValues = Array($SqlValues);
foreach ($SqlValues AS $Key => $Value)
if (is_numeric($Key))
$this -> BindValue((int) $Key + 1, $Value, self::PDOType($Value));
else
$this -> BindValue(':' . $Key, $Value, self::PDOType($Value));
return $this;
}
/**
* Executes query, measures the total time
*/
public function Execute($input_parameters = null) {
$Start = microtime(true);
parent::Execute($input_parameters);
$End = microtime(true);
$this->Duration = round($End - $Start, 4);
$this->Executed = true;
$this->ExecCount++;
return $this;
}
/**
* Executes the statement with bounded params
*
* @param array $SqlValues : Optional PDO Values to bind
* @return PDOStatementExtended instance
*/
public function Sql($SqlValues = array()) {
return $this->BindValues($SqlValues)->Execute();
}
/**
* SqlArray executes Query : returns the whole result set
*
* @param array $SqlValues : Optional PDO Values to bind
* @return Array
*/
public function SqlArray($SqlValues = array()) {
return $this->BindValues($SqlValues)->Execute()->FetchAll(PDO::FETCH_ASSOC);
}
/**
* SqlRow executes Query : returns the 1st row of your result set
*
* @param array $SqlValues : Optional PDO Values to bind
* @return Array
*/
public function SqlRow($SqlValues = array()) {
return $this->BindValues($SqlValues)->Execute()->Fetch(PDO::FETCH_ASSOC);
}
/**
* SqlColumn executes Query : returns the 1st column of your result set
*
* @param array $SqlValues : Optional PDO Values to bind
* @return Array
*/
public function SqlColumn($SqlValues = array()) {
return $this->BindValues($SqlValues)->Execute()->FetchAll(PDO::FETCH_COLUMN);
}
/**
* SqlValue executes Query : returns the 1st cell of your result set
*
* @param array $SqlValues : Optional PDO Values to bind
* @return String
*/
public function SqlValue($SqlValues = array()) {
return $this->BindValues($SqlValues)->Execute()->Fetch(PDO::FETCH_COLUMN);
}
/**
* SqlAssoc executes Query :
* If $DataType == self::TO_STRING : returns an associative array where the 1st column is the key and the 2nd is the value
* If $DataType == self::TO_STDCLASS : returns an associative array where the 1st column is the key the others are properties of an anonymous object
* If $DataType == self::TO_ARRAY_ASSOC : returns an associative array where the 1st column is the key the others are an associative array
* If $DataType == self::TO_ARRAY_INDEX : returns an associative array where the 1st column is the key the others are an indexed array
*
* @param array $SqlValues : PDO Values to bind
* @param int $DataType : type of data wanted
* @return Array
*/
public function SqlAssoc($SqlValues = array(), $DataType = self::TO_STRING) {
$Data = $this->BindValues($SqlValues)->Execute()->Fetch(PDO::FETCH_ASSOC);
if ($Data) :
$Keys = array_keys($Data);
$Result = Array();
if ($DataType == PDOExtended::TO_STDCLASS)
$Result = Array($Data[$Keys[0]] => (object) array_slice($Data, 1));
elseif ($DataType == PDOExtended::TO_ARRAY_ASSOC)
$Result = Array($Data[$Keys[0]] => array_slice($Data, 1));
elseif ($DataType == PDOExtended::TO_ARRAY_INDEX)
$Result = Array($Data[$Keys[0]] => array_values(array_slice($Data, 1)));
else // $DataType == PDOExtended::TO_STRING by default
$Result = Array($Data[$Keys[0]] => $Data[$Keys[1]]);
return $Result;
return $Result;
else :
return $Data;
endif;
}
/**
* SqlMultiAssoc executes Query :
* If $DataType == self::TO_STRING : returns an associative array where the 1st column is the key and the 2nd is the value
* If $DataType == self::TO_STDCLASS : returns an associative array where the 1st column is the key the others are properties of an anonymous object
* If $DataType == self::TO_ARRAY_ASSOC : returns an associative array where the 1st column is the key the others are an associative array
* If $DataType == self::TO_ARRAY_INDEX : returns an associative array where the 1st column is the key the others are an indexed array
*
* @param array $SqlValues : PDO Values to bind
* @param int $DataType : type of data wanted
* @return Array
*/
public function SqlMultiAssoc($SqlValues = array(), $DataType = self::TO_STRING) {
$Data = $this->BindValues($SqlValues)->Execute()->FetchAll(PDO::FETCH_ASSOC);
if (array_key_exists(0, $Data)) :
$Keys = array_keys($Data[0]);
$Result = Array();
foreach ($Data AS $Item)
if ($DataType == PDOExtended::TO_STDCLASS)
$Result[] = Array($Item[$Keys[0]] => (object) array_slice($Item, 1));
elseif ($DataType == PDOExtended::TO_ARRAY_ASSOC)
$Result[] = Array($Item[$Keys[0]] => array_slice($Item, 1));
elseif ($DataType == PDOExtended::TO_ARRAY_INDEX)
$Result[] = Array($Item[$Keys[0]] => array_values(array_slice($Item, 1)));
else // $DataType == PDOExtended::TO_STRING by default
$Result[] = Array($Item[$Keys[0]] => $Item[$Keys[1]]);
return $Result;
else :
return $Data;
endif;
}
/**
* PDOStatementExtended debug function
*
* @return PDOStatementExtended instance
* @author Beno!t POLASZEK - Jun 2013
*/
public function Debug() {
$this->Keywords = Array();
$this->Preview = preg_replace("#\t+#", "\t", $this->queryString);
# Case of question mark placeholders
if (array_key_exists(0, $this->BoundValues) && $this->BoundValues[0]['Parameter'] === 1)
foreach ($this->BoundValues AS $BoundParam)
$this->Preview = preg_replace("/([\?])/", self::DebugValue($BoundParam), $this->Preview, 1);
# Case of named placeholders
else
foreach ($this->BoundValues AS $boundValue)
$this->Keywords[] = $boundValue['Parameter'];
foreach ($this->Keywords AS $Word)
foreach ($this->BoundValues AS $BoundParam)
if ($BoundParam['Parameter'] == $Word)
$this->Preview = preg_replace("/(".$Word.")/i", self::DebugValue($BoundParam), $this->Preview);
return $this;
}
/**
* String context => query preview
*/
public function __toString() {
return $this->queryString;
}
/**
* Write access on private and protected properties : DENIED
*/
public function __set($Key, $Value) {
return false;
}
/**
* Read access on private and protected properties : TOLERATED
*/
public function __get($Key) {
return $this->$Key;
}
/**
* Add quotes or not for Debug() method
*/
private static function DebugValue($BoundParam) {
if (in_array($BoundParam['PDOType'], Array(PDO::PARAM_BOOL, PDO::PARAM_INT)))
return (int) $BoundParam['Value'];
elseif ($BoundParam['PDOType'] == PDO::PARAM_NULL)
return 'NULL';
else
return (string) "'". addslashes($BoundParam['Value']) . "'";
}
/**
* Transforms an indexed array into placeholders
* Example : Array(0, 22, 99) ==> '?,?,?'
* Usage : "WHERE VALUES IN (". PDOStatementExtended::PlaceHolders($MyArray) .")"
*
* @param array $Array
* @return string placeholder
* @author Beno!t POLASZEK - Jun 2013
*/
public static function PlaceHolders($Array = Array()) {
return implode(',', array_fill(0, count($Array), '?'));
}
/**
* PDO Automatic type binding
*
* @param mixed var
* @return PDO const
*/
public static function PDOType($Var) {
switch (strtolower(gettype($Var))) :
case 'string' :
return (strtoupper($Var) == 'NULL') ? PDO::PARAM_NULL : PDO::PARAM_STR;
case 'int' :
case 'integer' :
return PDO::PARAM_INT;
case 'double' :
case 'float' :
return PDO::PARAM_STR; // No float PDO type at the moment... :(
case 'bool' :
case 'boolean' :
return PDO::PARAM_BOOL;
case 'null' :
return PDO::PARAM_NULL;
default :
return PDO::PARAM_STR;
endswitch;
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/db/PDOExtended/README'
PDO Extended
===========
A PDO extension that will help your developer's life.
Features :
- Several methods like SqlArray(), Sqlrow(), SqlColumn(), SqlValue() that will help you to quickly retrieve a resultset
- You can disconnect, reconnect, pause the connection.
- Bind your values easily, example :
```php
$Ids = $Cnx->SqlColumn("SELECT Id FROM table WHERE CreationDate BETWEEN ? AND ?", ['2013-01-01', '2013-06-01']);
$Id = $Cnx->SqlValue("SELECT Id FROM table WHERE Id = ?", [35]);
$Id = $Cnx->SqlValue("SELECT Id FROM table WHERE Id = ?", 35); // You don't need an array if you just have 1 value to bind
$Row = $Cnx->SqlRow("SELECT * FROM table WHERE Name LIKE :Name AND Id >= :Id", ['Name' => 'foo%', 'Id' => 22]);
```
- Bind, Run and Debug your statements very easily :
```php
$Stmt = $Cnx->Prepare("SELECT Id FROM table WHERE CreationDate BETWEEN ? AND ?");
$Ids = $Stmt->SqlColumn(['2013-01-01', '2013-06-01']); // Fetches Ids in an indexed array
var_dump($Stmt->Debug()->Preview); // SELECT Id FROM table WHERE CreationDate BETWEEN '2013-01-01' AND '2013-06-01'
var_dump($Stmt->Debug()->Duration); // 0.004
```
- Create placeholders on the fly :
```php
$Ids = [2, 5, 8, 24, 26];
try {
$Rows = $Cnx->SqlArray("SELECT * FROM table WHERE Id IN (".PDOStatementExtended::PlaceHolders($Ids).")", $Ids);
}
catch (StmtException $e) {
var_dump($e->GetStmt()->queryString); // SELECT * FROM table WHERE Id IN (?, ?, ?, ?, ?)
var_dump($e->GetStmt()->Preview); // SELECT * FROM table WHERE Id IN (2, 5, 8, 24, 26)
}
// Also works with strings with automatic quote wrapping
$Dates = ['2013-01-01', '2013-06-01'];
try {
$Rows = $Cnx->SqlArray("SELECT * FROM table WHERE CreationDate IN (".PDOStatementExtended::PlaceHolders($Dates).")", $Dates);
}
catch (StmtException $e) {
var_dump($e->GetStmt()->queryString); // SELECT * FROM table WHERE CreationDate IN (?, ?)
var_dump($e->GetStmt()->Preview); // SELECT * FROM table WHERE CreationDate IN ('2013-01-01', '2013-06-01')
}
```
- You no longer need to deal with PDO::PARAM_INT, PDO::PARAM_STRING etc. since the PDO type is automatically set depending on the PHP type.
Full Example usage :
```php
require_once 'PDOExtended/PDOExtended.php';
define('PDO_DSN', 'mysql:host=localhost;dbname=test');
define('PDO_USERNAME', 'root');
define('PDO_PASSWORD', null);
// Normal call
$Cnx = new PDOExtended(PDO_DSN, PDO_USERNAME, PDO_PASSWORD);
// Singleton call
class db {
use PDOExtendedSingleton;
}
db::Cnx(PDO_DSN, PDO_USERNAME, PDO_PASSWORD);
$Tables = db::Cnx()->SqlColumn("SHOW TABLES");
// Let's create our working table...
$Cnx->Sql("CREATE TABLE IF NOT EXISTS
TVSeries (
Id TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(255),
Channel VARCHAR(40),
PRIMARY KEY (Id),
UNIQUE (Name)
) ENGINE=InnoDb");
// Or db::Cnx()->Sql(...) when using the singleton mode
// Example of insert with a prepared statement
$InsertStmt = $Cnx->Prepare("INSERT IGNORE INTO TVSeries SET Name = ?");
$TVSeries = Array('Games Of Thrones', 'The Big Bang Theory', 'Dexter');
// For each Series, we play the insert statement with a different value
foreach ($TVSeries AS $Series)
$InsertStmt->Sql($Series);
// $Series is mapped to the "Name" bound value - since it's a string, it'll be bound as PDO::PARAM_STR
// If $Series was an integer, it'd be bound as PDO::PARAM_INT automatically
// The expected parameter may also be an array, in case you have more values to bind
$InsertStmt = $Cnx->Prepare("INSERT IGNORE INTO TVSeries SET Name = :Name");
foreach ($TVSeries AS $Series)
$InsertStmt->Sql(Array('Name' => $Series));
// Now, let's update the previous rows with the Channel info.
$Channels = Array('HBO', 'CBS', 'ShowTime');
// You're not obliged to prepare your statement before executing them. It's the Sql() method's job.
$Cnx->Sql("UPDATE TVSeries SET Channel = ? WHERE Name = ?", Array($Channels[0], $TVSeries[0]));
$Cnx->Sql("UPDATE TVSeries SET Channel = :Channel WHERE Name LIKE :Name", Array('Channel' => $Channels[1], 'Name' => $TVSeries[1]));
$Cnx->Sql("UPDATE TVSeries SET Channel = :Channel WHERE Id = :Id", Array('Channel' => $Channels[2], 'Id' => 3)); // Id sera typé automatiquement en PDO::PARAM_INT car 2 est un entier
// Now, let's easily retrieve some infos.
// All the table into a multidimensionnal array.
var_dump($Cnx->SqlArray("SELECT * FROM TVSeries"));
// Juste the Big bang theory row
var_dump($Cnx->SqlRow("SELECT * FROM TVSeries WHERE Id = ?", 2));
// A list of series
var_dump($Cnx->SqlColumn("SELECT Name FROM TVSeries WHERE Channel IN (". PDOStatementExtended::PlaceHolders($Channels) .")", $Channels)); // La fonction PlaceHolders produira "IN (?, ?, ?)";
// What's the channel of Dexter ?
var_dump($Cnx->SqlValue("SELECT Channel FROM TVSeries WHERE Name LIKE :Name", Array('Name' => 'Dexter')));
// Another way to request it
var_dump($Cnx->SqlValue("SELECT Channel FROM TVSeries WHERE Name LIKE ?", Array('Dexter')));
// Another way to request it
var_dump($Cnx->SqlValue("SELECT Channel FROM TVSeries WHERE Name LIKE ?", 'Dexter'));
// Association key => value
var_dump($Cnx->SqlAssoc("SELECT Channel, Name FROM TVSeries WHERE Id = ?", 3));
// Association key => associative array
var_dump($Cnx->SqlAssoc("SELECT Channel, Id, Name FROM TVSeries WHERE Id = ?", 3, PDOExtended::TO_ARRAY_ASSOC));
// Association key => indexed array
var_dump($Cnx->SqlAssoc("SELECT Channel, Id, Name FROM TVSeries WHERE Id = ?", 3, PDOExtended::TO_ARRAY_INDEX));
// Association key => stdClass
var_dump($Cnx->SqlAssoc("SELECT Channel, Id, Name FROM TVSeries WHERE Id = ?", 3, PDOExtended::TO_STDCLASS));
// Association key => value, multiline version (array of keys => values)
var_dump($Cnx->SqlMultiAssoc("SELECT Channel, Name FROM TVSeries WHERE Id IN (?, ?)", Array(1, 2)));
// Association key => associative array, multiline version (array of keys => associative arrays)
var_dump($Cnx->SqlMultiAssoc("SELECT Channel, Id, Name FROM TVSeries WHERE Id IN (?, ?)", Array(1, 2), PDOExtended::TO_ARRAY_ASSOC));
// Association key => indexed array, multiline version (array of keys => indexed arrays)
var_dump($Cnx->SqlMultiAssoc("SELECT Channel, Id, Name FROM TVSeries WHERE Id IN (?, ?)", Array(1, 2), PDOExtended::TO_ARRAY_INDEX));
// Association key => stdClass, multiline version (array of keys => stdClasses)
var_dump($Cnx->SqlMultiAssoc("SELECT Channel, Id, Name FROM TVSeries WHERE Id IN (?, ?)", Array(1, 2), PDOExtended::TO_STDCLASS));
// You can also invoke all theses methods from a PDOStatementExtended object
var_dump($Cnx->Prepare("SELECT Channel, Id, Name FROM TVSeries WHERE Id IN (?, ?)")->SqlMultiAssoc(Array(2, 3), PDOExtended::TO_STDCLASS));
// How long the query has taken ?
$Stmt = $Cnx->Prepare("SELECT * FROM TVSeries WHERE Id = :Id OR Name LIKE :Name");
$Res = $Stmt->SqlArray(Array('Id' => 1, 'Name' => 'Dexter'));
var_dump($Stmt->Duration);
// What was the real query played ?
var_dump($Stmt->Debug()->Preview);
// You can disconnect : every call afterwards will result in a PDO Exception until you invoke the Reconnect() method
$Cnx->Disconnect();
// When disconnected, you can just call Reconnect without having to specify the dsn / username / password again
$Cnx->Reconnect();
// You can also Pause the connection. It actually disconnects from MySQl, but on the next call (Sql, Query, SqlArray etc) the Reconnect() method will automatically be called so you never have a "not connected" exception thrown
$Cnx->Pause();
// Why doing this ? When you have a big treatment to do (parsing a big xml for instance), this prevents from getting "sleep connections" issues
// The ping() method tells you wether or not you're effectively connected to MySQl
var_dump($Cnx->Ping());
// Every other PDO method is available... $Cnx->Query() ou $Cnx->SetAttribute(), etc.
wget 'https://sme10.lists2.roe3.org/pmnl3/include/db/PDOExtended/StmtException.php'
<?php
/**
* MIT License (MIT)
*
* Copyright (c) 2013 Beno!t POLASZEK
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* StmtException class
* @author Beno!t POLASZEK - 2013
*/
Class StmtException Extends PDOException {
protected $Stmt;
public function __construct($Message, $Code, PDOException $Exception, PDOStatementExtended $Stmt) {
parent::__construct($Message, $Code);
$this->Stmt = $Stmt;
}
public function GetStmt() {
return $this->Stmt;
}
}