Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Bom, vou deixar aqui a classe de Database que eu uso. Sei que já tem várias, mas acho que mais uma não faz mal :)
Eu implementei somente o que estava precisando nela, daí ficou pouca coisa (um CRUD simples, pra ser mais exato), mas de qualquer forma, ela ta aí pra quem quiser estudar/usar.
<?php
/**
* Database Access Object
*
* @package Database
* @author Raphael C. <raphael@engenhosweb.com.br>
* @copyright 2011 Raphael C.
* @license http://creativecommons.org/licenses/by/3.0/ Creative Commons Attribution 3.0 Unported License.
* @version SVN: $Id$
*/
class Database {
/**
* @access protected
* @var object
*/
protected $_dbh ;
/**
* @var string
*/
var $last_query ;
/**
* @var int
*/
var $insert_id ;
/**
* @var int
*/
var $affected_rows ;
/**
* @var string
*/
var $charset ;
/**
* @var bool
*/
var $debug ;
/**
* @var array
*/
var $trace ;
// -------------------------------------------------------------------------------
/**
* Connects to the database server and selects a database
*
* @return void
*/
function __construct( $host, $username, $passwd, $dbname, $charset = null, $debug = null ) {
/** Create a new mysql connection */
$this->_dbh = @mysql_connect( $host, $username, $passwd ) ;
@mysql_select_db( $dbname, $this->_dbh ) ;
/** Error reporting */
if ( mysql_errno( $this->_dbh ) ) {
throw new RuntimeException( mysql_error( $this->_dbh ), mysql_errno( $this->_dbh ) ) ;
return ;
}
/** Defines charset */
$this->debug( $debug ) ;
$this->charset( $charset ) ;
}
// -------------------------------------------------------------------------------
/**
* PHP5 style destructor and will run when database object is destroyed.
*
* @return void
*/
function __destruct() {
if ( $this->_dbh ) {
mysql_close( $this->_dbh ) ;
}
return true ;
}
// -------------------------------------------------------------------------------
/**
* Sets the default client character set
*
* @param string $charset <p>
* The charset to be set as default.
* If ommited, this function will only return the current charset.
* </p>
* @return mixed Returns the current charset on success or false on failure.
*/
function charset( $charset = null ) {
if ( is_null( $charset ) == false ) {
$set = function_exists( 'mysql_set_charset' ) ?
mysql_set_charset( $charset, $this->_dbh ) : @$this->query( $this->bind_params( 'SET NAMES %s;', $charset ) ) ;
if ( $set == false ) {
throw new UnexpectedValueException( 'Invalid or not supported character set <code>' . $charset . '</code>' ) ;
return false ;
}
$this->charset = $charset ;
}
return $this->charset ;
}
// -------------------------------------------------------------------------------
/**
* Sets the debug mode
*
* @param string $debug <p>
* The charset to be set as default.
* If ommited, this function will only return the current charset.
* </p>
* @return mixed Returns the current charset on success or false on failure.
*/
function debug( $debug = null ) {
if ( is_null( $debug ) == false ) {
$this->debug = $debug ;
}
return $this->debug ;
}
// -------------------------------------------------------------------------------
/**
* Executes a mysql query.
*
* @param string $query The query string.
* Data inside the query should be properly escaped.
* @return mixed Returns the insert id on INSERT, affected rows on DELETE|UPDATE|REPLACE|ALTER or
* a mysqli_result instance for another kinds of queries.
*/
function query( $query ) {
$dbh = &$this->_dbh ;
$start = $this->timer() ;
$q = @mysql_query( $query, $dbh ) ;
$time = $this->timer() - $start ;
/* Save last made query */
$this->last_query = $query ;
if ( mysql_errno() === 0 ) {
$return = null ;
/* Check if statement returns another kind of value */
if ( preg_match( "/^\\s*(DELETE|UPDATE|INSERT|REPLACE|ALTER) /i", $query ) == true ) {
/* Take note of the insert id */
if ( preg_match( "/^\\s*(INSERT|REPLACE) /i", $query ) == true ) {
$this->insert_id = mysql_insert_id( $dbh ) ;
}
/* Number of affected rows */
$return = $this->affected_rows = mysql_affected_rows( $dbh ) ;
} else {
/* The MySQL result itself */
$return = $q ;
}
if ( $this->debug == true ) {
$this->trace[ ] = array (
'time' => $time,
'query' => $query,
'affected_rows' => $this->affected_rows,
) ;
}
return $return ;
}
/* Error reporting. */
throw new ErrorException( mysql_error( $dbh ), mysql_errno( $dbh ), E_USER_WARNING ) ;
return false ;
}
// -------------------------------------------------------------------------------
/**
* Prepares a SQL query for safe execution.
*
* This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %f (float), %s (string).
* Does not support sign, padding, alignment, width or precision specifiers.
*
* @uses Database::bind_params_array()
*
* @param string $query Query statement with sprintf()-like placeholders
* @param mixed $args First variable to substitute into the query's placeholders
* @param mixed $... Further variables to substitute into the query's placeholders
*
* @return string Sanitized query string, false if there is an error
*/
function bind_params( $query ) {
$values = func_get_args() ;
array_shift( $values ) ;
return $this->bind_params_array( $query, $values ) ;
}
// -------------------------------------------------------------------------------
/**
* Prepares a SQL query for safe execution.
*
* This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %f (float), %s (string).
* Does not support sign, padding, alignment, width or precision specifiers.
*
* @see Database::bind_params()
*
* @param string $query Query statement with sprintf()-like placeholders
* @param array $args The array of variables to substitute into the query's placeholders
*
* @return string Sanitized query string, false if there is an error
*/
function bind_params_array( $query, array $args ) {
/* Escape strings */
array_walk( $args, array ( &$this, '_escape_string' ) ) ;
$query = str_replace( array ( "'%s'", '"%s"' ), '%s', $query ) ;
$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ) ;
return @vsprintf( $query, $args ) ;
}
// -------------------------------------------------------------------------------
/**
* Insert a row into a table.
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $data Data to insert (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @return mixed The number of rows inserted, or false on error.
*/
function insert( $table, array $data ) {
return $this->_insert_replace( $table, $data, 'INSERT' ) ;
}
// -------------------------------------------------------------------------------
/**
* Replace a row into a table.
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $data Data to insert (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @return mixed The number of rows inserted, or false on error.
*/
function replace( $table, array $data ) {
return $this->_insert_replace( $table, $data, 'REPLACE' ) ;
}
// -------------------------------------------------------------------------------
/**
* Update a row in the table
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $data Data to update (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
* @param int $limit Limit of rows to be updated
* @return mixed The number of rows updated, or false on error.
*/
function update( $table, array $data, array $where = array ( ), $limit = 0 ) {
$values = array ( ) ;
/* Check var type and assign %s for string, %f for float and %d for int */
foreach ( $data as $field => $value )
$values[ ] = '`' . $field . '`=' . $this->_get_type( $value ) ;
/* Compose the SQL and execute. */
$query = 'UPDATE `' . $table . '` SET ' . join( ', ', $values ) ;
$query .= sizeof( $where ) > 0 ?
$this->_where( $where ) : '' ;
$query .= $limit > 0 ?
' LIMIT ' . $limit : '' ;
$query .= ' ;' ;
$query = $this->bind_params_array( $query, array_merge( $data, $where ) ) ;
return $this->query( $query ) ;
}
// -------------------------------------------------------------------------------
/**
* Retrieve a row in the table
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
* @param int $limit Limit of rows to be deleted
* @return type
*/
function select( $table, $where = array ( ), $limit = 0 ) {
return $this->_select_delete( $table, $where, $limit, 'SELECT' ) ;
}
// -------------------------------------------------------------------------------
/**
* Delete a row in the table
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
* @param int $limit Limit of rows to be deleted
* @return type
*/
function delete( $table, $where = array ( ), $limit = 0 ) {
return $this->_select_delete( $table, $where, $limit, 'DELETE' ) ;
}
// -------------------------------------------------------------------------------
/**
* Helper function for delete and select.
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
* @param int $limit Limit of rows to be deleted
* @return type
*/
private function _select_delete( $table, $where, $limit, $type ) {
$type = strtoupper( $type ) ;
if ( in_array( $type, array ( 'DELETE', 'SELECT' ) ) == false ) {
throw new InvalidArgumentException( 'insert_replace() 3rd parameter should be equal to INSERT or REPLACE.' ) ;
return ;
}
/* Compose the SQL and execute. */
$query = $type . ' FROM `' . $table . '` ' ;
$query .= sizeof( $where ) > 0 ?
$this->_where( $where ) : '' ;
$query .= $limit > 0 ?
' LIMIT ' . $limit : '' ;
$query .= ' ;' ;
$query = $this->bind_params_array( $query, $where ) ;
return $this->query( $query ) ;
}
// -------------------------------------------------------------------------------
/**
* Helper function for insert and replace.
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $data Data to update (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @return mixed The number of rows updated, or false on error.
*/
private function _insert_replace( $table, array $data, $type ) {
$type = strtoupper( $type ) ;
$fields = array_keys( $data ) ;
if ( in_array( $type, array ( 'INSERT', 'REPLACE' ) ) == false ) {
throw new InvalidArgumentException( 'insert_replace() 3rd parameter should be equal to INSERT or REPLACE.' ) ;
return ;
}
/* Check var type and assign %s for string, %f for float and %d for int */
$values = array_map( array ( &$this, '_get_type' ), $data ) ;
/* Compose the SQL and execute. */
$query = $this->bind_params_array( $type . ' INTO `' . $table . '` (`' . join( '`, `', $fields ) . '`) VALUES (' . join( ', ', $values ) . ');', $data ) ;
return $this->query( $query ) ;
}
// -------------------------------------------------------------------------------
/**
* {@internal Missing Description}}
*
* @param type $message
* @param type $code
*/
function get_error() {
return array (
'error' => mysql_error( $this->_dbh ),
'errno' => mysql_errno( $this->_dbh ),
) ;
}
// -------------------------------------------------------------------------------
/**
* Escapes special characters in a string for use in a SQL statement
*
* @param string $unescaped_string The string that is to be escaped.
* @return string the escaped string, or false on error.
*/
function _escape_string( $string ) {
if ( $this->_dbh )
return mysql_real_escape_string( $string, $this->_dbh ) ;
else
return addslashes( $string ) ;
}
// -------------------------------------------------------------------------------
/**
* {@internal Missing Description}}
* @param type $data
* @return type
*/
private function _where( $data ) {
$where = array ( ) ;
foreach ( $data as $field => $value )
$where[ ] = '`' . $field . '`=' . $this->_get_type( $value ) ;
return ' WHERE (' . join( ' AND ', $where ) . ') ' ;
}
// -------------------------------------------------------------------------------
/**
* {@internal Missing Description}}
*
* @param mixed $var Variable
* @return string Type of variable
*/
private function _get_type( $var ) {
switch ( 1 ) {
case is_bool( $var ):
case is_long( $var ):
return '%d' ;
break ;
case is_double( $var ):
return '%f' ;
break ;
case is_string( $var ):
default:
return '%s' ;
break ;
}
}
// -------------------------------------------------------------------------------
/**
* {@internal Missing Description}}
*
* @return type
*/
function timer() {
list($usec, $sec) = explode( ' ', microtime() ) ;
return ( float ) $usec + ( float ) $sec ;
}
// -------------------------------------------------------------------------------
}Hmm.. Acho que não :mellow:
Certo, não deu pra analisar tudo, mas logo de cara, já tem duas coisas erradas que percebi ..
Note: The PHP 4 method of declaring a variable with the var keyword is still
supported for compatibility reasons (as a synonym for the public keyword).
In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.
Na verdade, ali diz que no php 5 antes do 5.1.3, a palavra-chave var gera erros com E_STRICT habilitado, dessa forma, alguém pode rodar seu code em um servidor em que geraria esse erro , mas mesmo assim, ainda é bom você utilizar um encapsulamento, utilizando as palavras-chave public, private, protected.
Vejo que você não conhece as mesmas .. então, uma breve explicação, para estas:
Public ou "publico" , define que tal propriedade ou método será publico, em termos de encapsulamento, ele será 'visível', a todos os membros da classe pai ou filha , como também poderá ser acessado(a) pelo contexto do objeto, o que é o contexto do objeto ? tudo que não está definido dentro da classe, por exemplo:
<?php
class MySQL {
public $userName ;
}
$MySQL = new MySQL();
$MySQL->userName = 'root' ; // definindo a variável no 'contexto' do objeto
Mas, se fazermos isso com uma propriedade protected ( protegida ) ou private ( privada ) , teríamos um erro, impedindo que a mesma seja definida ou sobrescrita por qualquer coisa no contexto do objeto, ou seja, tornando possível às definições da mesma, somente no escopo (dentro do objeto)
Vejamos então
<?php
class MySQL {
protected $userName ;
}
$MySQL = new MySQL();
$MySQL->userName = 'root' ; // Fatal Error
Então ao rodar o código, temos o seguinte erro : "Fatal error: Cannot access protected property MySQL::$userName" , ou seja, a variável é protegida e só pode ser definida por um método interno da classe, ou por algum objeto que herde esta classe, herança já é outros quinhentos ..
Logo então, temos a private (privada) , que só pode ser acessada pela classe que à define, ou seja, ninguém tem acesso, somente métodos da mesma classe, herança nesse caso, não pode definir uma propriedade privada, se você mudar a palavra-chave para 'private', vai ter um erro bem similar a mensagem de erro da protected ( exemplo acima ) .. "Fatal error: Cannot access private property MySQL::$userName"
Então, para você definir/recuperar valores de propriedades privadas, ou protected, você utiliza métodos getters e setters, que são responsáveis por esse trabalho, veja o exemplo:
<?php
class MySQL {
private $userName ;
public function setUserName ( $userName ) {
$this -> userName = $userName ;
}
public function getUserName ( ) {
return $this -> userName ;
}
}
$MySQL = new MySQL();
$MySQL -> setUserName ( 'root' ) ;
echo $MySQL -> getUserName ( ) ; // root
Lembrando que da mesma forma que as propriedades são privadas / publicas ou protegidas, os métodos também tem esse encapsulamento, de certa forma, se você definir um método como privado ou protegido, você não terá acesso a ele.
Segue um link que possa te dar um start-up em alguns conceitos e conhecimentos em Orientação a Objetos :seta: http://forum.imasters.com.br/forum/159-curso-de-php/
Boa Sorte, []'s
;)
Sim, sim eu sei disso.
Porém, quando você disse que estava faltando o encapsulamento, seria onde?
Com excessão de usar o var, que é questão de costume meu, não vi nada de errado.
Não sei se você percebeu, mas o próprio erro já disse, 'var' = 'public'.
>
var keyword is still supported for compatibility reasons (as a synonym for the public keyword).
Mas de qualquer forma, acho que os novatos vão aproveitar isso melhor que eu, para não dizer que foi inútil. (Sem ofensas).
Sim, exato, a var é um public, mas eu disse mais por questões de outras pessoas executarem o código em um servidor que geraria erro com STRICT ligado, entendeu ?
O encapsulamento te serve para manter as coisas que o usuário não pode fazer como serviço que só tais classes ou a própria classe pode usar ..
Corrigido de acordo com que o Andrey disse e um bug que eu não tinha visto que não fazia o select() funcionar.
<?php
/**
* Database Access Object
*
* @package Database
* @author Raphael C. <raphael@engenhosweb.com.br>
* @copyright 2011 Raphael C.
* @license http://creativecommo...icenses/by/3.0/ Creative Commons Attribution 3.0 Unported License.
* @version SVN: $Id$
*/
class Tug_Core_Database {
/**
* @access protected
* @var object
*/
protected $_dbh ;
/**
* @var array
*/
private $_trace ;
/**
* @var array
*/
private $_settings ;
/**
* @var string
*/
public $last_query ;
/**
* @var int
*/
public $insert_id ;
/**
* @var int
*/
public $affected_rows ;
/**
* @var int
*/
public $num_queries ;
/**
* Connects to the database server and selects a database.
*
* @return void
*/
function __construct( $host, $username, $passwd, $dbname, $charset = null, $debug = false, $pconnect = false ) {
/** Store our settings. */
$this->_settings[ 'host' ] = $host ;
$this->_settings[ 'username' ] = $username ;
$this->_settings[ 'passwd' ] = $passwd ;
$this->_settings[ 'dbname' ] = $dbname ;
/** Check if we're using the persistent handler. */
if ( $pconnect === true ) {
/** Then create a new mysql connection with it. */
$this->_dbh = @mysql_pconnect( $host, $username, $passwd ) ;
} else {
/** Or just use the "common" method. */
$this->_dbh = @mysql_connect( $host, $username, $passwd ) ;
}
/** Select the working database */
@mysql_select_db( $dbname, $this->_dbh ) ;
/** Error reporting */
if ( mysql_errno( $this->_dbh ) ) {
throw new RuntimeException( mysql_error( $this->_dbh ), mysql_errno( $this->_dbh ) ) ;
return ;
}
/** Defines charset */
$this->debug( $debug ) ;
$this->charset( $charset ) ;
}
/**
* PHP5 style destructor and will run when database object is destroyed.
*
* @return void
*/
function __destruct() {
if ( $this->_dbh ) {
mysql_close( $this->_dbh ) ;
}
return true ;
}
/**
* Sets the default client character set
*
* @param string $charset <p>
* The charset to be set as default.
* If ommited, this function will only return the current charset.
* </p>
* @return mixed Returns the current charset on success or false on failure.
*/
function charset( $charset = null ) {
if ( is_null( $charset ) == false ) {
$set = function_exists( 'mysql_set_charset' ) ?
mysql_set_charset( $charset, $this->_dbh ) : @$this->query( $this->bind_params( 'SET NAMES %s ;', $charset ) ) ;
if ( $set == false ) {
throw new UnexpectedValueException( 'Invalid or not supported character set <code>' . $charset . '</code>' ) ;
return false ;
}
$this->_settings[ 'charset' ] = $charset ;
}
return $this->_settings[ 'charset' ] ;
}
/**
* Sets the debug mode
*
* @param string $debug <p>
* The charset to be set as default.
* If ommited, this function will only return the current charset.
* </p>
* @return mixed Returns the current charset on success or false on failure.
*/
function debug( $debug = null ) {
if ( is_null( $debug ) == false ) {
$this->_settings[ 'debug' ] = $debug ;
}
return $this->_settings[ 'debug' ] ;
}
/**
* Executes a mysql query.
*
* @param string $query The query string.
* Data inside the query should be properly escaped.
* @return mixed Returns the insert id on INSERT, affected rows on DELETE|UPDATE|REPLACE|ALTER or
* a mysqli_result instance for another kinds of queries.
*/
function query( $query ) {
$dbh = &$this->_dbh ;
$start = $this->timer() ;
$q = @mysql_query( $query, $dbh ) ;
$time = $this->timer() - $start ;
/** Save last made query */
$this->last_query = $query ;
if ( mysql_errno() === 0 ) {
$return = null ;
/** Increment $num_queries */
$this->num_queries++ ;
/** Check if statement returns another kind of value */
if ( preg_match( "/^\\s*(DELETE|UPDATE|INSERT|REPLACE|ALTER) /i", $query ) == true ) {
/** Take note of the insert id */
if ( preg_match( "/^\\s*(INSERT|REPLACE) /i", $query ) == true ) {
$this->insert_id = mysql_insert_id( $dbh ) ;
}
/** Number of affected rows */
$return = $this->affected_rows = mysql_affected_rows( $dbh ) ;
} else {
/** The MySQL result itself */
$return = $q ;
}
if ( $this->debug() == true ) {
$this->_trace[ ] = array (
'name' => 'Query #' . $this->num_queries,
'time' => $time,
'query' => $query,
'affected' => $this->affected_rows
) ;
}
return $return ;
}
/** Error reporting. */
throw new ErrorException( mysql_error( $dbh ), mysql_errno( $dbh ), E_USER_WARNING ) ;
return false ;
}
/**
* Prepares a SQL query for safe execution.
*
* This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %f (float), %s (string).
* Does not support sign, padding, alignment, width or precision specifiers.
*
* @uses Database::bind_params_array()
*
* @param string $query Query statement with sprintf()-like placeholders
* @param mixed $args First variable to substitute into the query's placeholders
* @param mixed $... Further variables to substitute into the query's placeholders
*
* @return string Sanitized query string, false if there is an error
*/
function bind_params( $query ) {
$values = func_get_args() ;
array_shift( $values ) ;
return $this->bind_params_array( $query, $values ) ;
}
/**
* Prepares a SQL query for safe execution.
*
* This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %f (float), %s (string).
* Does not support sign, padding, alignment, width or precision specifiers.
*
* @see Database::bind_params()
*
* @param string $query Query statement with sprintf()-like placeholders
* @param array $args The array of variables to substitute into the query's placeholders
*
* @return string Sanitized query string, false if there is an error
*/
function bind_params_array( $query, array $args ) {
/** Escape strings */
array_walk( $args, array ( &$this, '_escape_string' ) ) ;
$query = str_replace( array ( "'%s'", '"%s"' ), '%s', $query ) ;
$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ) ;
return @vsprintf( $query, $args ) ;
}
/**
* Insert a row into a table.
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $data Data to insert (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @return mixed The number of rows inserted, or false on error.
*/
function insert( $table, array $data ) {
return $this->_insert_replace( $table, $data, 'INSERT' ) ;
}
/**
* Replace a row into a table.
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $data Data to insert (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @return mixed The number of rows inserted, or false on error.
*/
function replace( $table, array $data ) {
return $this->_insert_replace( $table, $data, 'REPLACE' ) ;
}
/**
* Update a row in the table
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $data Data to update (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
* @param int $limit Limit of rows to be updated
* @return mixed The number of rows updated, or false on error.
*/
function update( $table, array $data, array $where = array ( ), $limit = 0 ) {
$values = array ( ) ;
/** Check var type and assign %s for string, %f for float and %d for int */
foreach ( $data as $field => $value )
$values[ ] = '`' . $field . '`=' . $this->_get_type( $value ) ;
/** Compose the SQL and execute. */
$query = 'UPDATE `' . $table . '` SET ' . join( ', ', $values ) ;
$query .= sizeof( $where ) > 0 ?
$this->_where( $where ) : '' ;
$query .= $limit > 0 ?
' LIMIT ' . $limit : '' ;
$query .= ' ;' ;
$query = $this->bind_params_array( $query, array_merge( $data, $where ) ) ;
return $this->query( $query ) ;
}
/**
* Retrieve a row in the table
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
* @param int $limit Limit of rows to be deleted
* @return type
*/
function select( $table, $where = array ( ), $limit = 0 ) {
return $this->_select_delete( $table, $where, $limit, 'SELECT' ) ;
}
/**
* Delete a row in the table
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
* @param int $limit Limit of rows to be deleted
* @return type
*/
function delete( $table, $where = array ( ), $limit = 0 ) {
return $this->_select_delete( $table, $where, $limit, 'DELETE' ) ;
}
/**
* Helper function for delete and select.
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
* @param int $limit Limit of rows to be deleted
* @return type
*/
private function _select_delete( $table, $where, $limit, $type ) {
$type = strtoupper( $type ) ;
if ( in_array( $type, array ( 'DELETE', 'SELECT' ) ) == false ) {
throw new InvalidArgumentException( 'insert_replace() 3rd parameter should be equal to INSERT or REPLACE.' ) ;
return ;
}
/** Compose the SQL and execute. */
$query = ($type === 'SELECT') ?
'SELECT * ' : 'DELETE ' ;
$query .= ' FROM `' . $table . '` ' ;
$query .= sizeof( $where ) > 0 ?
$this->_where( $where ) : '' ;
$query .= $limit > 0 ?
' LIMIT ' . $limit : '' ;
$query .= ' ;' ;
$query = $this->bind_params_array( $query, $where ) ;
return $this->query( $query ) ;
}
/**
* Helper function for insert and replace.
*
* @see Database::query()
* @see Database::bind_params_array()
*
* @param string $table Table name
* @param array $data Data to update (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @return mixed The number of rows updated, or false on error.
*/
private function _insert_replace( $table, array $data, $type ) {
$type = strtoupper( $type ) ;
$fields = array_keys( $data ) ;
if ( in_array( $type, array ( 'INSERT', 'REPLACE' ) ) == false ) {
throw new InvalidArgumentException( 'insert_replace() 3rd parameter should be equal to INSERT or REPLACE.' ) ;
return ;
}
/** Check var type and assign %s for string, %f for float and %d for int */
$values = array_map( array ( &$this, '_get_type' ), $data ) ;
/** Compose the SQL and execute. */
$query = $this->bind_params_array( $type . ' INTO `' . $table . '` (`' . join( '`, `', $fields ) . '`) VALUES (' . join( ', ', $values ) . ');', $data ) ;
return $this->query( $query ) ;
}
/**
* {@internal Missing Description}}
*
* @param type $message
* @param type $code
*/
function get_error() {
return array (
'error' => mysql_error( $this->_dbh ),
'errno' => mysql_errno( $this->_dbh ),
) ;
}
/**
* Escapes special characters in a string for use in a SQL statement
*
* @param string $unescaped_string The string that is to be escaped.
* @return string the escaped string, or false on error.
*/
function _escape_string( $string ) {
if ( $this->_dbh )
return mysql_real_escape_string( $string, $this->_dbh ) ;
else
return addslashes( $string ) ;
}
/**
* {@internal Missing Description}}
* @param type $data
* @return type
*/
private function _where( $data ) {
$where = array ( ) ;
foreach ( $data as $field => $value )
$where[ ] = '`' . $field . '`=' . $this->_get_type( $value ) ;
return ' WHERE (' . join( ' AND ', $where ) . ') ' ;
}
/**
* {@internal Missing Description}}
*
* @param mixed $var Variable
* @return string Type of variable
*/
private function _get_type( $var ) {
switch ( 1 ) {
case is_bool( $var ):
case is_long( $var ):
return '%d' ;
case is_double( $var ):
return '%f' ;
case is_string( $var ):
default:
return '%s' ;
}
}
/**
* {@internal Missing Description}}
*
* @return type
*/
function timer() {
list($usec, $sec) = explode( ' ', microtime() ) ;
return ( float ) $usec + ( float ) $sec ;
}
}
Impressão minha ou tiraram o botão de editar o post? :huh:
>
Impressão minha ou tiraram o botão de editar o post? :huh:
Depois de um certo tempo, não é possível editar o post.
Hmmmmmm, não estas faltando um encapsulamento aí não ?