Accueil > > > EXTEND MYSQLI
EXTEND MYSQLI
Information sur la source
Description
Voila mon premier code objet oriente Ce code comporte 3 classes donc une principale : mysqli_access extends Mysqli et deux autres utilisees par la premiere Mysqli_access_stmt extends Mysqli_stmt, Mysqli_access_result extends Mysqli_results. J'ai principalement cree cette classe car dans mes cripts je voulais avoir seulement get_data(), insert_data(), update_data() et delete_data() comme actions et acceder a certaines proprietes comme num_rows juste par $objet->num_rows.
Source
- <?php
- /**
- * Msqli_exception
- *
- * @version 1
- * @author Julie.D
- * @link http://www.phpclasses.org/browse/package/5770.html
- */
-
- class Mysqli_exception extends Exception{
-
- public $_title;
- public $_class;
- public $_methode;
- public $_query;
-
-
- public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false){
-
- $this->_title = $title;
- $this->_class = $class;
- $this->_methode = $methode;
- $this->_query = $query;
-
- $this->eLogPath['DIR']='logs';
- $this->eLogPath['FILE']='Mysqli_error';
- $this->eLogPath['EXTENSION']='.txt';
-
- parent::__construct($message,$code);
- }
-
- public function __tostring(){
- $str ='<p><b>' .$this->_title.'</b><br />';
- $str.='Class : ' .$this->_class. ' - Using Methode '.$this->_methode.'(). <br />';
- $str.='Error : ('.$this->getCode().') '.$this->getMessage().'. <br />';
- if($this->_query) {
- $str.='Executing :' .$this->_query. '. <br />';
- }
-
- $str.='Script : '.$this->getFile().' - Line : '.$this->getLine().'. <br />';
- $str.= 'Trace :<br /> ';
- $str.=$this->Trace__tostring().' <br /></p>';
-
- return $str;
- }
-
- public function Trace__tostring(){
-
- $trace_array=$this->getTrace();
- $trace_str=null;
- foreach($trace_array as $trace) {
- $trace_str .=$trace['file']. ' - Line '.$trace['line'].'<br />';
- $trace_str .='Class ' .$trace['class'].' - Using Methode ' .$trace['function'].'() <br />' ;
- }
- return $trace_str;
- }
- }
-
- class Mysqli_exception_connect extends Mysqli_exception {
-
- public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false) {
-
- if( is_null( $title ) ){
- $title='Connection error';
- }
- parent :: __construct($message,$code,$class,$methode,$title);
-
-
- }
- }
-
- Class Mysqli_Exception_config extends Mysqli_exception {
-
-
- public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false) {
-
- if( is_null( $title ) ){
- $title='Configuration Error [Mysqli_config.php]';
- }
- parent :: __construct($message,$code,$class,$methode,$title);
- }
- }
-
- Class Mysqli_exception_query extends Mysqli_exception {
-
- public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false) {
-
- if( is_null( $title ) ){
- $title='QUERY error';
- }
- if( preg_match('/prepare/',$message) ){
- $message=preg_replace('/prepare/','',$message);
- $message=$message. 'Could not prepare the query';
- $code=1;
- }
- if( preg_match('/bind_param/',$message) ){
- $message=preg_replace('/bind_param/','',$message);
- $message=$message. 'Could not bind parameter of the query';
- $code=2;
- }
- if( preg_match('/execute/',$message) ){
- $message=preg_replace('/execute/','',$message);
- $message=$message. 'Could not execute the query';
- $code=3;
- }
- if( preg_match('/store_result/',$message) ){
- $message=preg_replace('/store_result/','',$message);
- $message=$message. 'Could not store result of the statement';
- $code=5;
- }
-
- if( preg_match('/bind_result/',$message) ){
- $message=preg_replace('/bind_result/','',$message);
- $message=$message. 'Could not execute the query';
- $code=5;
- }
-
- parent :: __construct($message,$code,$class,$methode,$title,$query);
-
-
- }
- }
-
-
- class Mysqli_exception_param extends Mysqli_exception {
-
- public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false) {
-
- if( is_null( $title ) ){
- $title='Parametre error';
- }
- if( preg_match('/object/',$message) ){
- $message=preg_replace('/object/','',$message);
- $message=$message. 'must be an object';
- $code=1;
- }
- if( preg_match('/string/',$message) ){
- $message=preg_replace('/string/','',$message);
- $message=$message. 'must be a string';
- $code=2;
- }
- if( preg_match('/array/',$message) ){
- $message=preg_replace('/array/','',$message);
- $message=$message. 'must be a array';
- $code=3;
- }
- parent :: __construct($message,$code,$class,$methode,$title);
-
-
- }
- }
- ?>
-
-
- <?php
- /*Mysqli_config*/
-
- self::$option['SHOW_EXCEPTIONS']=true; //will show exceptions if true
- self::$option['SHOW_MESSAGE']='<p>An error as occur The Administrator has been informed</p>'; //will show this message if SHOW_EXCEPTION=false
- self::$option['DIE_ON_EXCEPTION']=false; // will make script die when an exception is caught
-
- self::$option['AUTOCONNECT']=true; //will connect to database when create object
-
-
- //optional can be set when create object.
- $this->login['HOST']='localhost';
- $this->login['USER']='root';
- $this->login['PASSWORD']='';
- $this->login['DATABASE']='perso';
- $this->login['TABLE']=false; //table name, optiona
-
- ?>
-
- <?php
- /**
- * Msqli_access
- *
- * @version 1.1
- * @author Julie.D
- * @link http://www.phpclasses.org/browse/package/5770.html
- *
- * TODO: return affected_rows for inser, update, delete data;
- */
-
-
- require '\mysqli_stmt_class.php';
- require '\mysqli_result_class.php';
- require '\build_query_string_class.php';
- require '\mysqli_exception_class.php';
-
-
- class mysqli_access extends mysqli{
-
- protected static $option=array(); //config options
- protected $login=array(); //config login
-
- public $table=null; //to declare in script $object->table='tablename';
- public $fieldlist=array(); //list of field names of $this->table
-
- private $last_query; //to hold the last query
-
- private $stmt; //new object of class msqli_access_stmt
- private $result; //new object of class mysqli_access_result
-
- private $param_array=array(); //to create $param_array to bind parametre
-
- public $num_rows;
-
- public static $ErrorTrace=array();
-
- /*__construct
- * @ Set class properties : $host
- * : $user
- * : $pass
- */
- public function __construct($login=null,$option=null) {
-
- require '/mysqli_config.php';
- if( is_array( $login ) ) {
- foreach( $login as $key=>$value ) {
- $this->login[$key]=$value;
- }
- }
- if( is_array( $option ) ) {
- foreach( $option as $key=>$value ) {
- self::$option[$key]=$value;
- }
- }
- if( self::$option['AUTOCONNECT'] === true ) {
- $this->connect($this->login['DATABASE']);
- }
- }
-
-
- /* Connect to the database
- * @ Argument : $db : database name
- * @ Connect : parent function __construct.
- */
- public function connect($db=null){
- try{
- if( is_null($db) ){
- Throw new mysqli_exception_config('Database not set',null,get_class($this),__FUNCTION__ );
- } else {
- parent::connect($this->login['HOST'], $this->login['USER'],$this->login['PASSWORD'], $db);
- if( $this -> connect_error ) {
- Throw new Mysqli_exception_connect($this->connect_error, $this->connect_errno,__FUNCTION__);
- } else return true;
- }
- }
- catch(Mysqli_exception_config $e) {
- self::handle_exception($e);
- return false;
- }catch(Mysqli_exception_connect $e) {
- self::handle_exception($e);
- return false;
- }
- }
-
- /* handle exceptions :
- * @Argument : $e :object of exception class
- * if $this->option['SHOW_EXCEPTIONS'] = true it will display exceptions on screen
- * = false it will keep trace of exception in an array
- * if $this->option['SHOW_EXCEPTIONS'] = true script will die when an exception is caught
- * trace of error when no
- */
-
-
- public function handle_exception($e){
- if( self::$option['SHOW_EXCEPTIONS'] === true ){
- if( self::$option['DIE_ON_EXCEPTION'] === true ){
- die( $e->__tostring() );
- }
- else echo $e->__tostring();
- } else {
- $error_message=$this->option['ERROR_MESSAGE'];
- echo $error_message;
- self::$ErrorTrace[]=array ( 'date' => date('d/m/y H:i:s'),
- 'num' => $e->getCode(),
- 'msg' => $e->getMessage(),
- 'class' => $e->_class,
- 'func' => $e->_methode
- );
-
- if( self::$option['DIE_ON_EXCEPTION'] === true ){
- die();
- }
- }
- }
-
- /* set_table
- * if $this->table is null and $this->login['TABLE'] it will trigger an error.
- * if $this->table is null it will set teh table to select to $this->login['TABLE']
- * @ Return true if $this->table is set.
- */
-
- public function set_table(){
- try{
- if( ! is_null($this->table) ){
- return true;
- } elseif( ! $this->login['TABLE'] === false ) {
- $this->table=$this->login['TABLE'];
- return true;
-
- }else {
- throw new Mysqli_exception_config('You did not set $table property',0,get_class($this),__FUNCTION__);
- }
- }catch(Mysqli_exception_config $e) {
- self::handle_exception($e);
- return false;
- }
- }
-
- /*Get_Data from $this->table
- * Has to have $line as get_data(__LINE__) to trigger error.
- * Arguments are optionals
- * $fields : to build field clause
- * $wherearray : to build WHERE clause
- * $group : to build GROUP BY clause
- * $sort : to build ORDER BY clause
- * $limit : to build LIMIT clause
- * @ BuildQueryString
- * @ Prepare, Bind_param, Execute
- * @ Use function fetch() of class mysql_access_stmt
- * @ Return data as an array
- */
- function get_data($fields=null,$wherearray=null,$group=null,$sort=null,$limit=null) {
-
- if( $this->set_table() === false){
- return false;
- }
- BuildQueryString::$table=$this->table;
- $query=BuildQueryString::Get_select($fields,$wherearray,$group,$sort,$limit);
- $this->param_array=BuildQueryString::$param_array;
-
- if ( $query === false ) {
- return false;
- }
- if ( $this->prep_bind_execute($query,$this->param_array) === false ) {
- return false;
- } else {
- $data = $this->stmt->fetch();
- if( $data === false ) {
- return false;
- } else {
- $this->num_rows=$this->stmt->num_rows;
- $this->stmt->close();
- unset($this->stmt);
- return $data;
- }
- }
- }
-
- /*Insert_data into $this->table
- * @ Arguments : $values : string or array : values to insert into the table
- * @ BuildQueryString
- * @ Prepare, Bind_param, Execute
- */
- public function insert_data($values) {
- if( $this->set_table() === false){
- return false;
- }
- BuildQueryString::$table=$this->table;
- $query=BuildQueryString::Get_insert($values);
- $this->param_array=BuildQueryString::$param_array;
- if ( $query === false ) {
- return false;
- }
- if( $this->prep_bind_execute($query,$this->param_array) === false ) {
- return false;
- } else {
- $this->stmt->close();
- unset($this->stmt);
- return true;
- }
- }
-
- /*Update_data into $this->table
- * @ Arguments : $wherearray : array
- * : $values : string or array
- * Optional: $fields : has to be as $values type if not null
- * @ BuildQueryString
- * @ Prepare, Bind_param, Execute
- */
- public function update_data($wherearray,$values,$fields=null) {
- if( $this->set_table() === false){
- return false;
- }
- BuildQueryString::$table=$this->table;
- $query=BuildQueryString::Get_update($values,$fields,$wherearray);
- $this->param_array=BuildQueryString::$param_array;
-
- if ( $query === false){
- return false;
- }
- if( ! $this->prep_bind_execute($query,$this->param_array) ) {
- return false;
- } else {
- $this->stmt->close();
- unset($this->stmt);
- return true;
- }
- }
-
- /*Delete_data from $this->table
- * @ Arguments : $wherearray : array
- * @ BuildQueryString
- * @ Prepare, Bind_param, Execute
- */
- public function delete_data($wherearray) {
- if( $this->set_table() === false){
- return false;
- }
- BuildQueryString::$table=$this->table;
- $query=BuildQueryString::Get_delete($wherearray);
- $this->param_array=BuildQueryString::$param_array;
- if( $query === false ){
- return false;
- }
- if( ! $this->prep_bind_execute($query,$this->param_array) ) {
- return false;
- }else{
- $this->stmt->close();
- unset($this->stmt);
- return true;
- }
- }
-
- /*get fields names from $this->table
- * @ BuildQueryString
- * @ Prepare, Bind_param, Execute
- * @ Get result_metadata
- * @ create new object $this->result from the class mysqli_access_result
- * @ Use fetch_list() from $this->result
- * @ Return $this->fieldlist populated with fields names of $this->table
- */
- public function Get_table_fields($tablename=false){
- if( $tablename=== false ){
- $tablename=$this->table;
- }
- BuildQueryString::$table = $tablename;
- $query=BuildQueryString::Get_select();
-
- if( $query === false ) {
- return false;
- }
- if( ! $this->prep_bind_execute($query) ){
- return false;
- }
-
- $metadata=$this->stmt->result_metadata();
- $this->stmt->close();
- unset($this->result);
-
- if( $metadata=== false) {
- return false;
- }
- $this->result=new mysqli_access_result($this);
- $this->fieldlist=$this->result->Fields_list($metadata);
- unset($this->result);
- if( $this->fieldlist === false){
- return false;
- } else return $this->fieldlist;
-
- }
-
- /*Prepare Bind execute statment
- * @ Arguments : $query : statement to be prepared.
- * : $param_array if got 1 argument or more bind_param()
- * @ Prepare, bind_param(), execute()
- */
- private function prep_bind_execute($query,$param_array=array()){
-
- if( $this->prepare($query) ) {
- if( count($param_array)>0 ) {
- $this->bind_param($param_array);
- }
- $this->execute();
- return true;
- } else return false;
- }
- /*Prepare statment
- * @ Argument : $query : statement to be prepared.
- * @ Create new object $this->stmt from class mysqli_stmt_access
- * Or Trigger Error
- * @ return new object $this->stmt
- */
- public function prepare($query){
-
- $this->last_query=$query;
- $this->stmt=new mysqli_access_stmt($this, $this->last_query );
-
- if( $this->stmt->error ) {
- unset($this->stmt);
- return false;
- } else return $this->stmt;
- }
-
- /*Bind parametres
- * @ Argument : $param_array : array
- * @ Use function bind_param of class mysqli_stmt_access
- */
- public function bind_param($param_array){
-
- try{
- if( ! is_array($param_array) ){
- Throw new Mysqli_exception_param('1st parameter array',null,get_class($this),__FUNCTION__);
- }
- if( ! $this->stmt->bind_param($param_array) ){
- Throw new Mysqli_exception_query('bind_param',null,get_class($this),__FUNCTION__,null,$this->last_query);
- } else return true;
- } catch(Mysqli_exception_param $e) {
- $this->handle_exception($e);
- return false;
- } catch(Mysqli_exception_query $e) {
- $this->handle_exception($e);
- return false;
- }
- }
-
- /*Execute
- * @ Use function Execute of class mysqli_stmt_access
- */
- public function execute(){
- Try {
- if( ! $this->stmt->execute() ) {
- Throw new Mysqli_exception_query('execute',null,get_class($this),__FUNCTION__,null,$this->last_query);
- } else return true;
- } catch(Mysqli_exception_query $e) {
- $this->handle_exception($e);
- return false;
- }
- }
- }
-
- ?>
-
- <?php
- /**
- * Msqli_access_stmt
- *
- * @version 1.1
- * @author Julie.D
- * @link http://www.phpclasses.org/browse/package/5770.html
- *
- * TODO : function affected_rows();
- */
-
-
-
- class mysqli_access_stmt extends mysqli_stmt{
-
- protected static $option=array(); //config options
- protected $login=array(); //config login
-
- public static $ErrorTrace=array();
- private $last_stmt; //to hold last statement
-
- protected $data=array(); //store data to be returned as an array
-
-
-
-
- public function __construct($link, $stmt) {
- require '\mysqli_config.php';
- $this->last_stmt=$stmt;
- try{
- if ( ! is_object($link) ) {
- Throw new Mysqli_exception_param('1st parameter object',0,get_class($this),__FUNCTION__);
- }
- if ( ! is_string( $stmt) ){
- Throw new Mysqli_exception_param('1st parameter string',0,get_class($this),__FUNCTION__);
- }
- parent::__construct($link, $stmt) ;
-
- if( $this->error ) {
- Throw new Mysqli_exception_query($this->error,$this->errno,get_class($this),__FUNCTION__,null,$this->last_stmt);
- } else return true;
- }catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- unset($this);
- return false;
- }catch(Mysqli_exception_query $e) {
- Mysqli_access::handle_exception($e);
- unset($this);
- return false;
- }
-
- }
-
-
- /* GET_PARAM TYPES set the type string i.d or s
- * @ Argument : $param : string, integer, double or otehr
- * @ Redurn the type of the param as a string
- */
- function Get_param_type($param){
- if( is_integer($param ) ){
- $type='i';
- } elseif( is_double($param) ){
- $type='d';
- } elseif( is_string($param) ){
- $type='s';
- } else {
- $type='s';
- }
- return $type;
- }
-
- /* Get type string of param_array
- * @ Arguments :$param_array accepts array
- * @ Return a string with the type of each argument of the array
- */
-
- function Get_type_string($param_array) {
- $type_str=NULL;
- try{
- if( ! is_array($param_array) ){
- Throw new Mysqli_exception_param('1st parameter array',null,get_class($this),__FUNCTION__);
- } else {
- foreach($param_array as $key=>$param){
- $type=self::Get_param_type($param);
- if( is_null($type_str) ) {
- $type_str=$type;
- } else {
- $type_str .=$type;
- }
- }
- return $type_str;
- }
- }catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- /* BIND_PARAM
- * @ Argument : $param_array : array
- * @ Bind_param()
- */
- function bind_param($param_array){
- try{
- if( ! is_array($param_array) ){
- Throw new Mysqli_exception_param('1st parameter array',null,get_class($this),__FUNCTION__);
- } else {
- $bind_array=array();
- $type_str=self::Get_type_string($param_array);
- $bind_array[0]=$type_str;
-
- foreach($param_array as $key=>$param){
- $bind_array[]=&$param_array[$key];
- }
- if ( ! call_user_func_array('parent::bind_param',$bind_array) ) {
-
- Throw new Mysqli_exception_query('bind_param',null,get_class($this),__FUNCTION__,null,$this->last_stmt);
- }
- return true;
- }
- }catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }catch(Mysqli_exception_query $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- /* BIND RESULT
- * @ Argument :$field_array : array
- */
-
- function bind_result($field_array){
- try{
- if( ! is_array($field_array) ){
- Throw new Mysqli_exception_param('1st parameter array',null,__FUNCTION__);
- } elseif( ! call_user_func_array('parent::bind_result',$field_array) ) {
- Throw new Mysqli_exception_query('bind_result',null,get_class($this),__FUNCTION__,null,$this->last_stmt);
- }else return true;
- }catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }catch(Mysqli_exception_query $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- function execute() {
- try{
- parent::execute();
- if( $this->error ) {
- Throw new Mysqli_exception_query($this->error ,$this->errno,get_class($this),__FUNCTION__,null,$this->last_stmt);
- } else return true;
- }catch(Mysqli_exception_query $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
-
- }
-
- function store_result() {
- try{
- parent::store_result();
- if( $this->error ) {
- Throw new Mysqli_exception_query($this->error ,$this->errno,get_class($this),__FUNCTION__,null,$this->last_stmt);
- } else return true;
- }catch(Mysqli_exception_query $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- /*FETCH
- * Has to be use after
- * mysqli->prepare, mysqli->bind_param , mysqli ->execute
- * @ parent Store results
- * @ bind results depending num of field
- * @ access to properties $this->field_count, $this->num_rows
- * @ parent fetch()
- * @ Return data as an array
- */
- public function fetch(){
-
- if( ! $this->store_result() ) {
- return false;
- }
- $result_set=array();
- for($i=0 ; $i<$this->field_count ;$i++ ) {
- $result_set[]=&$row[$i];
- }
- if( ! $this->bind_result($result_set) ) {
- return false;
- }
- for( $i=0 ; $i<$this->num_rows ; $i++) {
- parent::fetch() ;
- $temp=array();
- foreach( $result_set as $k=>$v ) {
- $temp[$k]=$v;
- }
- array_push($this->data,$temp);
- }
- return $this->data;
- }
-
-
- public function result_metadata(){
- try{
- $metadata=parent::result_metadata();
- if( ! is_object($metadata) ){
- Throw new Mysqli_exception_query('Could not get metadata',null,get_class($this),__FUNCTION__);
- } else return $metadata;
- }catch(Mysqli_exception_query $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- }
- ?>
-
- <?php
- /**
- * Msqli_access_result
- *
- * @version 1.1
- * @author Julie.D
- * @link http://www.phpclasses.org/browse/package/5770.html
- *
- */
-
-
-
- class mysqli_access_result extends mysqli_result {
-
- public $fieldlist=array();
- protected static $option;
- public static $ErrorTrace=array();
-
- public function __construct($mysqli){
- try{
- require '\mysqli_config.php';
- if( ! is_object($mysqli) ){
- Throw new Mysqli_exception_param('1st parameter object',0,get_class($this),__FUNCTION__);
- }
- parent::__construct($mysqli);
- } catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- /*Field_list
- * @ Argument : $metadata : object.
- * @ Return fields name of the table as an array
- */
- public function Fields_list($metadata){
- try{
- if( !is_object($metadata) ){
- Throw new Mysqli_exception_param('1st argument object',0,get_class($this),__FUNCTION__);
- }
- $finfo=$metadata->fetch_fields();
- foreach ($finfo as $val) {
- $this->fieldlist[]=$val->name;
- }
- return $this->fieldlist;
- } catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- }
- ?>
-
- <?php
- <?php
- /**
- * BuildQueryString
- *
- * @version 1
- * @author Julie.D
- * @link http://www.phpclasses.org/browse/package/5770.html
- */
-
- Class BuildQueryString{
-
- public static $table; //tablename to create strings
- public static $param_array; //param_array to return for bind_param
- public static $ErrorTrace=array();
-
- public function __construct($table_name){
- self::$table=$table_name;
- self::$param_array =array();
- }
-
- /*Build SELECT values_str
- * The string is build for the table this->table which has to be define.
- * @Arguments : are all optional
- * $fields : string or array
- * $wherearray : array
- * $group : string
- * $sort : string or array
- * $limit : string
- * @ Return string
- * For exemple : 'SELECT * FROM table'
- * : 'SELECT field1 FROM table WHERE field1=?'
- */
- public static function Get_select($fields=null,$wherearray=null,$group=null,$sort=null,$limit=null) {
- $field_str = ( is_null($fields) ) ? '*' : self::Get_fields($fields);
- self::$param_array=array();
-
- if( !is_null($wherearray) ) {
- $where_str=self::Get_where($wherearray);
- }else $where_str=null;
- if( ! is_null($group) ) {
- $group_str=" GROUP BY $group ";
- } else $group_str=null;
- if( !is_null($sort) ) {
- $sort_str=self::Get_sort($sort);
- } else $sort_str=null;
- if (! is_null($limit) && is_numeric($limit) ) {
- $limit= " LIMIT " . $limit;
- } else $limit_str=null;
- if( $field_str === false || $where_str === false || $group_str=== false || $sort_str=== false || $limit_str=== false ){
- return false;
- } else {
- $query='SELECT '.$field_str.' FROM ' .self::$table.$where_str.$group_str.$sort_str.$limit_str;
- return $query;
- }
- }
-
- /*Build INSERT string
- * The string is build for the table this->table which has to be define.
- * @ Argument : $values : array
- * @ Populate self::$param_array
- * @ Return string
- * For exemple : 'INSERT into table VALUES (?,?,?)
- *
- */
- public static function Get_insert($values) {
-
- try{
- if( ! is_array($values) ) {
- Throw new Mysqli_exception_param('1st parameter array',null,'BuildQueryString',__FUNCTION__);
-
- } else {
- $values_str=NULL;
- self::$param_array=array();
- $values_str=self::Get_fields($values,false,true);
- $query='INSERT INTO '. self::$table.' VALUES ('.$values_str.')';
- return $query;
- }
- } catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- /*Build UPDATE string
- * The string is build for the table this->table which has to be define.
- * @ Arguments : $values : string or array
- * : $fields : string or array
- * : has to be as $values type,
- * : if is null get_table_fields()
- * : $wherearray : array
- * @ Populate self::$param_array
- * @ Return string
- * For exemple : 'UPDATE table SET $field1=?,$field2=? WHERE $field1=?
- */
- public static function Get_update($values,$fields,$wherearray){
- try{
- self::$param_array=array();
- if( is_null($fields) ){
- $sqli=new Mysqli_access();
- $fields=$sqli->Get_table_fields(self::$table);
- $sqli->close();
- unset($sqli);
- }
- if ( is_array($fields) || is_array($values) ){
- if( ! is_array($fields) ) {
- Throw new Mysqli_exception_param('1st parameter array',null,'BuildQueryString',__FUNCTION__);
- }
- if( ! is_array($values) ) {
- Throw new Mysqli_exception_param('2nd parameter array',null,'BuildQueryString',__FUNCTION__);
- }
- if( count($values) != count($fields) ){
- Throw new Mysqli_exception_param('$values and $fields arguments count are different',6,get_class($this),__FUNCTION__);
- } else{
- $values_str=self::Get_fields($fields,$values,false);
- }
- } else{
- $values_str=$fields .'=?';
- self::$param_array[]=$values;
- }
- $where_str=self::Get_where($wherearray);
- $query= 'UPDATE '.self::$table.' SET '.$values_str.$where_str ;
- return $query;
- } catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
-
- /*Build DELETE string
- * The string is build for the table this->table which has to be define.
- * @ Arguments : $wherearray : array
- * @ Populate self::$param_array
- * @ Return string
- * For exemple : 'DELETE FROM table WHERE $field1=?'
- */
- public static function Get_delete($wherearray) {
- self::$param_array=array();
- $where_str=self::Get_where($wherearray);
- $query='DELETE FROM '.self::$table. $where_str;
-
- return $query;
- }
-
- /*Build Field String (to use with get_select)
- * @ Arguments: $fields : string or array
- * For Exemple : $fields=$field1
- * : $fields=array($filed1,$filed2, .......)
- * Optionals: $values or $bind Thus populate self::$param_array
- * : $values : array or string [ $bind has to be false ]
- * : $bind : boleen true of false
- * @ Return field string as : '$field1,$field2,... '
- * : if $values : '$field1=?','$field2=?'
- * : if $bind : '?,?'
- */
- public static function Get_fields($fields,$values=false,$bind=false) {
- $field_str=NULL;
- if( is_array($fields) ) {
- foreach($fields as $key=>$field) {
- if( is_null($field_str) ) {
- $field_str = ( $bind ) ? '?' :"$field";
- }else{
- $field_str .= ( $bind ) ? ', ?' :", $field";
- }
- if($values){
- $field_str .= '=?';
- self::$param_array[]=$values[$key];
- } else{
- self::$param_array[]=$field;
- }
- }
- } elseif( is_string($fields) ) {
- $field_str = $fields;
- if( $values ){
- $field_str = $fields . '=?';
- self::$param_array[]=$values;
- }
- }
- return $field_str;
- }
-
-
-
- /*Build WHERE string
- * @Argument : $wherearray : Array
- * For Exemple : $wherearray[$field1]=$value1;
- * : $wherearray=array( $field1=>$value1, $field2=>$value2)
- * @ Populate self::$param_array as : self::$param_array=($value1,$value2);
- * @ Return Where string as : 'Where $field1= ? AND $field1= ?'
- */
- public static function Get_where($wherearray) {
- try{
- if( ! is_array($wherearray) ) {
- Throw new Mysqli_exception_param('1st parameter array',null,'BuildQueryString',__FUNCTION__);
- return false;
- } else {
- $where_str=NULL;
- foreach($wherearray as $field=>$value) {
- if( is_null($where_str) ) {
- $where_str =" WHERE $field=? ";
- self::$param_array[]=$value;
- } else {
- $where_str .=" AND $field=? ";
- self::$param_array[]=$value;
- }
- }
- return $where_str;
- }
- }catch(Mysqli_exception_param $e) {
- Mysqli_access::handle_exception($e);
- return false;
- }
- }
-
- /*Build SORT clause (to use with get_select)
- * @ Argument : $sort : string or array
- * For Exemple : $sort=$field;
- * : $sort=array($filed1,$field2);
- * ->Can specify the order to sort as $order= 'DESC' or 'ASC'
- * : $sort[$field1]=$order1;
- * : $sort=array( $field1=>$order1, $field2=>$order2)
- * @ Return Sort string as : ' ORDER BY $field1'
- * : ' ORDER BY $field1 $order1 '
- */
- public static function Get_sort($sort){
- $sort_str=NULL;
-
- if( is_array($sort) ) {
- foreach($sort as $field=>$order) {
- $field = ( is_numeric($field) ) ? NULL : $field;
- if( is_null($sort_str) ) {
- $sort_str= " ORDER BY $field $order ";
- } else {
- $sort_str .= ", $field $order";
- }
- }
- } elseif( is_string($sort) ) {
- $sort_str = " ORDER BY $sort";
- }
- return $sort_str;
- }
- }
-
-
- ?>
<?php
/**
* Msqli_exception
*
* @version 1
* @author Julie.D
* @link http://www.phpclasses.org/browse/package/5770.html
*/
class Mysqli_exception extends Exception{
public $_title;
public $_class;
public $_methode;
public $_query;
public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false){
$this->_title = $title;
$this->_class = $class;
$this->_methode = $methode;
$this->_query = $query;
$this->eLogPath['DIR']='logs';
$this->eLogPath['FILE']='Mysqli_error';
$this->eLogPath['EXTENSION']='.txt';
parent::__construct($message,$code);
}
public function __tostring(){
$str ='<p><b>' .$this->_title.'</b><br />';
$str.='Class : ' .$this->_class. ' - Using Methode '.$this->_methode.'(). <br />';
$str.='Error : ('.$this->getCode().') '.$this->getMessage().'. <br />';
if($this->_query) {
$str.='Executing :' .$this->_query. '. <br />';
}
$str.='Script : '.$this->getFile().' - Line : '.$this->getLine().'. <br />';
$str.= 'Trace :<br /> ';
$str.=$this->Trace__tostring().' <br /></p>';
return $str;
}
public function Trace__tostring(){
$trace_array=$this->getTrace();
$trace_str=null;
foreach($trace_array as $trace) {
$trace_str .=$trace['file']. ' - Line '.$trace['line'].'<br />';
$trace_str .='Class ' .$trace['class'].' - Using Methode ' .$trace['function'].'() <br />' ;
}
return $trace_str;
}
}
class Mysqli_exception_connect extends Mysqli_exception {
public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false) {
if( is_null( $title ) ){
$title='Connection error';
}
parent :: __construct($message,$code,$class,$methode,$title);
}
}
Class Mysqli_Exception_config extends Mysqli_exception {
public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false) {
if( is_null( $title ) ){
$title='Configuration Error [Mysqli_config.php]';
}
parent :: __construct($message,$code,$class,$methode,$title);
}
}
Class Mysqli_exception_query extends Mysqli_exception {
public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false) {
if( is_null( $title ) ){
$title='QUERY error';
}
if( preg_match('/prepare/',$message) ){
$message=preg_replace('/prepare/','',$message);
$message=$message. 'Could not prepare the query';
$code=1;
}
if( preg_match('/bind_param/',$message) ){
$message=preg_replace('/bind_param/','',$message);
$message=$message. 'Could not bind parameter of the query';
$code=2;
}
if( preg_match('/execute/',$message) ){
$message=preg_replace('/execute/','',$message);
$message=$message. 'Could not execute the query';
$code=3;
}
if( preg_match('/store_result/',$message) ){
$message=preg_replace('/store_result/','',$message);
$message=$message. 'Could not store result of the statement';
$code=5;
}
if( preg_match('/bind_result/',$message) ){
$message=preg_replace('/bind_result/','',$message);
$message=$message. 'Could not execute the query';
$code=5;
}
parent :: __construct($message,$code,$class,$methode,$title,$query);
}
}
class Mysqli_exception_param extends Mysqli_exception {
public function __construct($message,$code,$class='unknow',$methode='unknow',$title=null,$query=false) {
if( is_null( $title ) ){
$title='Parametre error';
}
if( preg_match('/object/',$message) ){
$message=preg_replace('/object/','',$message);
$message=$message. 'must be an object';
$code=1;
}
if( preg_match('/string/',$message) ){
$message=preg_replace('/string/','',$message);
$message=$message. 'must be a string';
$code=2;
}
if( preg_match('/array/',$message) ){
$message=preg_replace('/array/','',$message);
$message=$message. 'must be a array';
$code=3;
}
parent :: __construct($message,$code,$class,$methode,$title);
}
}
?>
<?php
/*Mysqli_config*/
self::$option['SHOW_EXCEPTIONS']=true; //will show exceptions if true
self::$option['SHOW_MESSAGE']='<p>An error as occur The Administrator has been informed</p>'; //will show this message if SHOW_EXCEPTION=false
self::$option['DIE_ON_EXCEPTION']=false; // will make script die when an exception is caught
self::$option['AUTOCONNECT']=true; //will connect to database when create object
//optional can be set when create object.
$this->login['HOST']='localhost';
$this->login['USER']='root';
$this->login['PASSWORD']='';
$this->login['DATABASE']='perso';
$this->login['TABLE']=false; //table name, optiona
?>
<?php
/**
* Msqli_access
*
* @version 1.1
* @author Julie.D
* @link http://www.phpclasses.org/browse/package/5770.html
*
* TODO: return affected_rows for inser, update, delete data;
*/
require '\mysqli_stmt_class.php';
require '\mysqli_result_class.php';
require '\build_query_string_class.php';
require '\mysqli_exception_class.php';
class mysqli_access extends mysqli{
protected static $option=array(); //config options
protected $login=array(); //config login
public $table=null; //to declare in script $object->table='tablename';
public $fieldlist=array(); //list of field names of $this->table
private $last_query; //to hold the last query
private $stmt; //new object of class msqli_access_stmt
private $result; //new object of class mysqli_access_result
private $param_array=array(); //to create $param_array to bind parametre
public $num_rows;
public static $ErrorTrace=array();
/*__construct
* @ Set class properties : $host
* : $user
* : $pass
*/
public function __construct($login=null,$option=null) {
require '/mysqli_config.php';
if( is_array( $login ) ) {
foreach( $login as $key=>$value ) {
$this->login[$key]=$value;
}
}
if( is_array( $option ) ) {
foreach( $option as $key=>$value ) {
self::$option[$key]=$value;
}
}
if( self::$option['AUTOCONNECT'] === true ) {
$this->connect($this->login['DATABASE']);
}
}
/* Connect to the database
* @ Argument : $db : database name
* @ Connect : parent function __construct.
*/
public function connect($db=null){
try{
if( is_null($db) ){
Throw new mysqli_exception_config('Database not set',null,get_class($this),__FUNCTION__ );
} else {
parent::connect($this->login['HOST'], $this->login['USER'],$this->login['PASSWORD'], $db);
if( $this -> connect_error ) {
Throw new Mysqli_exception_connect($this->connect_error, $this->connect_errno,__FUNCTION__);
} else return true;
}
}
catch(Mysqli_exception_config $e) {
self::handle_exception($e);
return false;
}catch(Mysqli_exception_connect $e) {
self::handle_exception($e);
return false;
}
}
/* handle exceptions :
* @Argument : $e :object of exception class
* if $this->option['SHOW_EXCEPTIONS'] = true it will display exceptions on screen
* = false it will keep trace of exception in an array
* if $this->option['SHOW_EXCEPTIONS'] = true script will die when an exception is caught
* trace of error when no
*/
public function handle_exception($e){
if( self::$option['SHOW_EXCEPTIONS'] === true ){
if( self::$option['DIE_ON_EXCEPTION'] === true ){
die( $e->__tostring() );
}
else echo $e->__tostring();
} else {
$error_message=$this->option['ERROR_MESSAGE'];
echo $error_message;
self::$ErrorTrace[]=array ( 'date' => date('d/m/y H:i:s'),
'num' => $e->getCode(),
'msg' => $e->getMessage(),
'class' => $e->_class,
'func' => $e->_methode
);
if( self::$option['DIE_ON_EXCEPTION'] === true ){
die();
}
}
}
/* set_table
* if $this->table is null and $this->login['TABLE'] it will trigger an error.
* if $this->table is null it will set teh table to select to $this->login['TABLE']
* @ Return true if $this->table is set.
*/
public function set_table(){
try{
if( ! is_null($this->table) ){
return true;
} elseif( ! $this->login['TABLE'] === false ) {
$this->table=$this->login['TABLE'];
return true;
}else {
throw new Mysqli_exception_config('You did not set $table property',0,get_class($this),__FUNCTION__);
}
}catch(Mysqli_exception_config $e) {
self::handle_exception($e);
return false;
}
}
/*Get_Data from $this->table
* Has to have $line as get_data(__LINE__) to trigger error.
* Arguments are optionals
* $fields : to build field clause
* $wherearray : to build WHERE clause
* $group : to build GROUP BY clause
* $sort : to build ORDER BY clause
* $limit : to build LIMIT clause
* @ BuildQueryString
* @ Prepare, Bind_param, Execute
* @ Use function fetch() of class mysql_access_stmt
* @ Return data as an array
*/
function get_data($fields=null,$wherearray=null,$group=null,$sort=null,$limit=null) {
if( $this->set_table() === false){
return false;
}
BuildQueryString::$table=$this->table;
$query=BuildQueryString::Get_select($fields,$wherearray,$group,$sort,$limit);
$this->param_array=BuildQueryString::$param_array;
if ( $query === false ) {
return false;
}
if ( $this->prep_bind_execute($query,$this->param_array) === false ) {
return false;
} else {
$data = $this->stmt->fetch();
if( $data === false ) {
return false;
} else {
$this->num_rows=$this->stmt->num_rows;
$this->stmt->close();
unset($this->stmt);
return $data;
}
}
}
/*Insert_data into $this->table
* @ Arguments : $values : string or array : values to insert into the table
* @ BuildQueryString
* @ Prepare, Bind_param, Execute
*/
public function insert_data($values) {
if( $this->set_table() === false){
return false;
}
BuildQueryString::$table=$this->table;
$query=BuildQueryString::Get_insert($values);
$this->param_array=BuildQueryString::$param_array;
if ( $query === false ) {
return false;
}
if( $this->prep_bind_execute($query,$this->param_array) === false ) {
return false;
} else {
$this->stmt->close();
unset($this->stmt);
return true;
}
}
/*Update_data into $this->table
* @ Arguments : $wherearray : array
* : $values : string or array
* Optional: $fields : has to be as $values type if not null
* @ BuildQueryString
* @ Prepare, Bind_param, Execute
*/
public function update_data($wherearray,$values,$fields=null) {
if( $this->set_table() === false){
return false;
}
BuildQueryString::$table=$this->table;
$query=BuildQueryString::Get_update($values,$fields,$wherearray);
$this->param_array=BuildQueryString::$param_array;
if ( $query === false){
return false;
}
if( ! $this->prep_bind_execute($query,$this->param_array) ) {
return false;
} else {
$this->stmt->close();
unset($this->stmt);
return true;
}
}
/*Delete_data from $this->table
* @ Arguments : $wherearray : array
* @ BuildQueryString
* @ Prepare, Bind_param, Execute
*/
public function delete_data($wherearray) {
if( $this->set_table() === false){
return false;
}
BuildQueryString::$table=$this->table;
$query=BuildQueryString::Get_delete($wherearray);
$this->param_array=BuildQueryString::$param_array;
if( $query === false ){
return false;
}
if( ! $this->prep_bind_execute($query,$this->param_array) ) {
return false;
}else{
$this->stmt->close();
unset($this->stmt);
return true;
}
}
/*get fields names from $this->table
* @ BuildQueryString
* @ Prepare, Bind_param, Execute
* @ Get result_metadata
* @ create new object $this->result from the class mysqli_access_result
* @ Use fetch_list() from $this->result
* @ Return $this->fieldlist populated with fields names of $this->table
*/
public function Get_table_fields($tablename=false){
if( $tablename=== false ){
$tablename=$this->table;
}
BuildQueryString::$table = $tablename;
$query=BuildQueryString::Get_select();
if( $query === false ) {
return false;
}
if( ! $this->prep_bind_execute($query) ){
return false;
}
$metadata=$this->stmt->result_metadata();
$this->stmt->close();
unset($this->result);
if( $metadata=== false) {
return false;
}
$this->result=new mysqli_access_result($this);
$this->fieldlist=$this->result->Fields_list($metadata);
unset($this->result);
if( $this->fieldlist === false){
return false;
} else return $this->fieldlist;
}
/*Prepare Bind execute statment
* @ Arguments : $query : statement to be prepared.
* : $param_array if got 1 argument or more bind_param()
* @ Prepare, bind_param(), execute()
*/
private function prep_bind_execute($query,$param_array=array()){
if( $this->prepare($query) ) {
if( count($param_array)>0 ) {
$this->bind_param($param_array);
}
$this->execute();
return true;
} else return false;
}
/*Prepare statment
* @ Argument : $query : statement to be prepared.
* @ Create new object $this->stmt from class mysqli_stmt_access
* Or Trigger Error
* @ return new object $this->stmt
*/
public function prepare($query){
$this->last_query=$query;
$this->stmt=new mysqli_access_stmt($this, $this->last_query );
if( $this->stmt->error ) {
unset($this->stmt);
return false;
} else return $this->stmt;
}
/*Bind parametres
* @ Argument : $param_array : array
* @ Use function bind_param of class mysqli_stmt_access
*/
public function bind_param($param_array){
try{
if( ! is_array($param_array) ){
Throw new Mysqli_exception_param('1st parameter array',null,get_class($this),__FUNCTION__);
}
if( ! $this->stmt->bind_param($param_array) ){
Throw new Mysqli_exception_query('bind_param',null,get_class($this),__FUNCTION__,null,$this->last_query);
} else return true;
} catch(Mysqli_exception_param $e) {
$this->handle_exception($e);
return false;
} catch(Mysqli_exception_query $e) {
$this->handle_exception($e);
return false;
}
}
/*Execute
* @ Use function Execute of class mysqli_stmt_access
*/
public function execute(){
Try {
if( ! $this->stmt->execute() ) {
Throw new Mysqli_exception_query('execute',null,get_class($this),__FUNCTION__,null,$this->last_query);
} else return true;
} catch(Mysqli_exception_query $e) {
$this->handle_exception($e);
return false;
}
}
}
?>
<?php
/**
* Msqli_access_stmt
*
* @version 1.1
* @author Julie.D
* @link http://www.phpclasses.org/browse/package/5770.html
*
* TODO : function affected_rows();
*/
class mysqli_access_stmt extends mysqli_stmt{
protected static $option=array(); //config options
protected $login=array(); //config login
public static $ErrorTrace=array();
private $last_stmt; //to hold last statement
protected $data=array(); //store data to be returned as an array
public function __construct($link, $stmt) {
require '\mysqli_config.php';
$this->last_stmt=$stmt;
try{
if ( ! is_object($link) ) {
Throw new Mysqli_exception_param('1st parameter object',0,get_class($this),__FUNCTION__);
}
if ( ! is_string( $stmt) ){
Throw new Mysqli_exception_param('1st parameter string',0,get_class($this),__FUNCTION__);
}
parent::__construct($link, $stmt) ;
if( $this->error ) {
Throw new Mysqli_exception_query($this->error,$this->errno,get_class($this),__FUNCTION__,null,$this->last_stmt);
} else return true;
}catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
unset($this);
return false;
}catch(Mysqli_exception_query $e) {
Mysqli_access::handle_exception($e);
unset($this);
return false;
}
}
/* GET_PARAM TYPES set the type string i.d or s
* @ Argument : $param : string, integer, double or otehr
* @ Redurn the type of the param as a string
*/
function Get_param_type($param){
if( is_integer($param ) ){
$type='i';
} elseif( is_double($param) ){
$type='d';
} elseif( is_string($param) ){
$type='s';
} else {
$type='s';
}
return $type;
}
/* Get type string of param_array
* @ Arguments :$param_array accepts array
* @ Return a string with the type of each argument of the array
*/
function Get_type_string($param_array) {
$type_str=NULL;
try{
if( ! is_array($param_array) ){
Throw new Mysqli_exception_param('1st parameter array',null,get_class($this),__FUNCTION__);
} else {
foreach($param_array as $key=>$param){
$type=self::Get_param_type($param);
if( is_null($type_str) ) {
$type_str=$type;
} else {
$type_str .=$type;
}
}
return $type_str;
}
}catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
/* BIND_PARAM
* @ Argument : $param_array : array
* @ Bind_param()
*/
function bind_param($param_array){
try{
if( ! is_array($param_array) ){
Throw new Mysqli_exception_param('1st parameter array',null,get_class($this),__FUNCTION__);
} else {
$bind_array=array();
$type_str=self::Get_type_string($param_array);
$bind_array[0]=$type_str;
foreach($param_array as $key=>$param){
$bind_array[]=&$param_array[$key];
}
if ( ! call_user_func_array('parent::bind_param',$bind_array) ) {
Throw new Mysqli_exception_query('bind_param',null,get_class($this),__FUNCTION__,null,$this->last_stmt);
}
return true;
}
}catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
return false;
}catch(Mysqli_exception_query $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
/* BIND RESULT
* @ Argument :$field_array : array
*/
function bind_result($field_array){
try{
if( ! is_array($field_array) ){
Throw new Mysqli_exception_param('1st parameter array',null,__FUNCTION__);
} elseif( ! call_user_func_array('parent::bind_result',$field_array) ) {
Throw new Mysqli_exception_query('bind_result',null,get_class($this),__FUNCTION__,null,$this->last_stmt);
}else return true;
}catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
return false;
}catch(Mysqli_exception_query $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
function execute() {
try{
parent::execute();
if( $this->error ) {
Throw new Mysqli_exception_query($this->error ,$this->errno,get_class($this),__FUNCTION__,null,$this->last_stmt);
} else return true;
}catch(Mysqli_exception_query $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
function store_result() {
try{
parent::store_result();
if( $this->error ) {
Throw new Mysqli_exception_query($this->error ,$this->errno,get_class($this),__FUNCTION__,null,$this->last_stmt);
} else return true;
}catch(Mysqli_exception_query $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
/*FETCH
* Has to be use after
* mysqli->prepare, mysqli->bind_param , mysqli ->execute
* @ parent Store results
* @ bind results depending num of field
* @ access to properties $this->field_count, $this->num_rows
* @ parent fetch()
* @ Return data as an array
*/
public function fetch(){
if( ! $this->store_result() ) {
return false;
}
$result_set=array();
for($i=0 ; $i<$this->field_count ;$i++ ) {
$result_set[]=&$row[$i];
}
if( ! $this->bind_result($result_set) ) {
return false;
}
for( $i=0 ; $i<$this->num_rows ; $i++) {
parent::fetch() ;
$temp=array();
foreach( $result_set as $k=>$v ) {
$temp[$k]=$v;
}
array_push($this->data,$temp);
}
return $this->data;
}
public function result_metadata(){
try{
$metadata=parent::result_metadata();
if( ! is_object($metadata) ){
Throw new Mysqli_exception_query('Could not get metadata',null,get_class($this),__FUNCTION__);
} else return $metadata;
}catch(Mysqli_exception_query $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
}
?>
<?php
/**
* Msqli_access_result
*
* @version 1.1
* @author Julie.D
* @link http://www.phpclasses.org/browse/package/5770.html
*
*/
class mysqli_access_result extends mysqli_result {
public $fieldlist=array();
protected static $option;
public static $ErrorTrace=array();
public function __construct($mysqli){
try{
require '\mysqli_config.php';
if( ! is_object($mysqli) ){
Throw new Mysqli_exception_param('1st parameter object',0,get_class($this),__FUNCTION__);
}
parent::__construct($mysqli);
} catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
/*Field_list
* @ Argument : $metadata : object.
* @ Return fields name of the table as an array
*/
public function Fields_list($metadata){
try{
if( !is_object($metadata) ){
Throw new Mysqli_exception_param('1st argument object',0,get_class($this),__FUNCTION__);
}
$finfo=$metadata->fetch_fields();
foreach ($finfo as $val) {
$this->fieldlist[]=$val->name;
}
return $this->fieldlist;
} catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
}
?>
<?php
<?php
/**
* BuildQueryString
*
* @version 1
* @author Julie.D
* @link http://www.phpclasses.org/browse/package/5770.html
*/
Class BuildQueryString{
public static $table; //tablename to create strings
public static $param_array; //param_array to return for bind_param
public static $ErrorTrace=array();
public function __construct($table_name){
self::$table=$table_name;
self::$param_array =array();
}
/*Build SELECT values_str
* The string is build for the table this->table which has to be define.
* @Arguments : are all optional
* $fields : string or array
* $wherearray : array
* $group : string
* $sort : string or array
* $limit : string
* @ Return string
* For exemple : 'SELECT * FROM table'
* : 'SELECT field1 FROM table WHERE field1=?'
*/
public static function Get_select($fields=null,$wherearray=null,$group=null,$sort=null,$limit=null) {
$field_str = ( is_null($fields) ) ? '*' : self::Get_fields($fields);
self::$param_array=array();
if( !is_null($wherearray) ) {
$where_str=self::Get_where($wherearray);
}else $where_str=null;
if( ! is_null($group) ) {
$group_str=" GROUP BY $group ";
} else $group_str=null;
if( !is_null($sort) ) {
$sort_str=self::Get_sort($sort);
} else $sort_str=null;
if (! is_null($limit) && is_numeric($limit) ) {
$limit= " LIMIT " . $limit;
} else $limit_str=null;
if( $field_str === false || $where_str === false || $group_str=== false || $sort_str=== false || $limit_str=== false ){
return false;
} else {
$query='SELECT '.$field_str.' FROM ' .self::$table.$where_str.$group_str.$sort_str.$limit_str;
return $query;
}
}
/*Build INSERT string
* The string is build for the table this->table which has to be define.
* @ Argument : $values : array
* @ Populate self::$param_array
* @ Return string
* For exemple : 'INSERT into table VALUES (?,?,?)
*
*/
public static function Get_insert($values) {
try{
if( ! is_array($values) ) {
Throw new Mysqli_exception_param('1st parameter array',null,'BuildQueryString',__FUNCTION__);
} else {
$values_str=NULL;
self::$param_array=array();
$values_str=self::Get_fields($values,false,true);
$query='INSERT INTO '. self::$table.' VALUES ('.$values_str.')';
return $query;
}
} catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
/*Build UPDATE string
* The string is build for the table this->table which has to be define.
* @ Arguments : $values : string or array
* : $fields : string or array
* : has to be as $values type,
* : if is null get_table_fields()
* : $wherearray : array
* @ Populate self::$param_array
* @ Return string
* For exemple : 'UPDATE table SET $field1=?,$field2=? WHERE $field1=?
*/
public static function Get_update($values,$fields,$wherearray){
try{
self::$param_array=array();
if( is_null($fields) ){
$sqli=new Mysqli_access();
$fields=$sqli->Get_table_fields(self::$table);
$sqli->close();
unset($sqli);
}
if ( is_array($fields) || is_array($values) ){
if( ! is_array($fields) ) {
Throw new Mysqli_exception_param('1st parameter array',null,'BuildQueryString',__FUNCTION__);
}
if( ! is_array($values) ) {
Throw new Mysqli_exception_param('2nd parameter array',null,'BuildQueryString',__FUNCTION__);
}
if( count($values) != count($fields) ){
Throw new Mysqli_exception_param('$values and $fields arguments count are different',6,get_class($this),__FUNCTION__);
} else{
$values_str=self::Get_fields($fields,$values,false);
}
} else{
$values_str=$fields .'=?';
self::$param_array[]=$values;
}
$where_str=self::Get_where($wherearray);
$query= 'UPDATE '.self::$table.' SET '.$values_str.$where_str ;
return $query;
} catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
/*Build DELETE string
* The string is build for the table this->table which has to be define.
* @ Arguments : $wherearray : array
* @ Populate self::$param_array
* @ Return string
* For exemple : 'DELETE FROM table WHERE $field1=?'
*/
public static function Get_delete($wherearray) {
self::$param_array=array();
$where_str=self::Get_where($wherearray);
$query='DELETE FROM '.self::$table. $where_str;
return $query;
}
/*Build Field String (to use with get_select)
* @ Arguments: $fields : string or array
* For Exemple : $fields=$field1
* : $fields=array($filed1,$filed2, .......)
* Optionals: $values or $bind Thus populate self::$param_array
* : $values : array or string [ $bind has to be false ]
* : $bind : boleen true of false
* @ Return field string as : '$field1,$field2,... '
* : if $values : '$field1=?','$field2=?'
* : if $bind : '?,?'
*/
public static function Get_fields($fields,$values=false,$bind=false) {
$field_str=NULL;
if( is_array($fields) ) {
foreach($fields as $key=>$field) {
if( is_null($field_str) ) {
$field_str = ( $bind ) ? '?' :"$field";
}else{
$field_str .= ( $bind ) ? ', ?' :", $field";
}
if($values){
$field_str .= '=?';
self::$param_array[]=$values[$key];
} else{
self::$param_array[]=$field;
}
}
} elseif( is_string($fields) ) {
$field_str = $fields;
if( $values ){
$field_str = $fields . '=?';
self::$param_array[]=$values;
}
}
return $field_str;
}
/*Build WHERE string
* @Argument : $wherearray : Array
* For Exemple : $wherearray[$field1]=$value1;
* : $wherearray=array( $field1=>$value1, $field2=>$value2)
* @ Populate self::$param_array as : self::$param_array=($value1,$value2);
* @ Return Where string as : 'Where $field1= ? AND $field1= ?'
*/
public static function Get_where($wherearray) {
try{
if( ! is_array($wherearray) ) {
Throw new Mysqli_exception_param('1st parameter array',null,'BuildQueryString',__FUNCTION__);
return false;
} else {
$where_str=NULL;
foreach($wherearray as $field=>$value) {
if( is_null($where_str) ) {
$where_str =" WHERE $field=? ";
self::$param_array[]=$value;
} else {
$where_str .=" AND $field=? ";
self::$param_array[]=$value;
}
}
return $where_str;
}
}catch(Mysqli_exception_param $e) {
Mysqli_access::handle_exception($e);
return false;
}
}
/*Build SORT clause (to use with get_select)
* @ Argument : $sort : string or array
* For Exemple : $sort=$field;
* : $sort=array($filed1,$field2);
* ->Can specify the order to sort as $order= 'DESC' or 'ASC'
* : $sort[$field1]=$order1;
* : $sort=array( $field1=>$order1, $field2=>$order2)
* @ Return Sort string as : ' ORDER BY $field1'
* : ' ORDER BY $field1 $order1 '
*/
public static function Get_sort($sort){
$sort_str=NULL;
if( is_array($sort) ) {
foreach($sort as $field=>$order) {
$field = ( is_numeric($field) ) ? NULL : $field;
if( is_null($sort_str) ) {
$sort_str= " ORDER BY $field $order ";
} else {
$sort_str .= ", $field $order";
}
}
} elseif( is_string($sort) ) {
$sort_str = " ORDER BY $sort";
}
return $sort_str;
}
}
?>
Conclusion
Je ne suis aps developpeur apres avoir lu et relu sur ce sujet je me suis lancee, peut etre je m y suis mal prise, les conseils seront les bienvenus. Il reste a faire sur ces classes dont developper Mysqli_result et ameliorer ma gestion d erreur pourrait etre dans une classe a part plus generale (je reflechie la dessus). ->chose faite mais surement loin d etre parfaite toujous ouverte aux commentaures
Historique
- 04 novembre 2009 00:01:51 :
- Ajout d options : mysqli_config.php
Class Mysqli_exception pour gerer les erreurs
separation des function pour construire les strings dans une class a part
- 05 novembre 2009 16:33:27 :
- $Option is static so can be share with BuilsQueryString class when call Mysqli_access::handle_exception()
- 06 novembre 2009 19:53:05 :
- minor change
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Creer MySQL database [ par pluton83fr ]
Slt Je suis un debutant en php, Je suis en train d installer un portail :Neocrome http://www.neocrome.net Et il me dise ca!!Mais le pb c'est que je n
probleme de tchat php [ par linkinpar236737 ]
j'ai un probleme de tchat dans mon site, j'ai acheté un flashchat, utilisant le php, et quand j'essaye de l'installer, il faut mettre : Database Name,
pb avec CREATE DATABASE [ par Joleroy ]
Bonjour a tous,J' ai ecrit ce petit bout de code qui crée un utilisateur, lui creer un base de donnée, et lui donne des droit sur cette 
Phpmyvisites et mysql [ par flopad ]
Bonjour,J'ai récupéré phpmyvisites pour l'utiliser sur mon intranet.j'ai un soucis lors de l'installation, ca me dit "localhost" databa
Erreur MySQL [ par coockiesch ]
Salut! Je viens d'installer, sur mon ordi, Apache2, MySQL, PHP5 et PhpMyAdmin. On m'a demandé de choisir l'extension mysqli, je choisi mysqli (pa
problème mysql : Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource [ par wizard512 ]
je sui entrain de créer un script et je rencontre l'érreur suivante:==>mysql_query(): supplied argument is not a valid MySQL-Link re
Lister les BD dans mysql [ par rad92 ]
Bonjour,Je ne comprends pas pourquoi ma formule ne marche pas :<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR
MySQL DataBase [ par MAsterC ]
Bonjour,J'aimerais savoir s'il y a une limite de lignes dans chaque table dans une base de données ou c'est à l'infini.Merci d'avance. ----------
Afficher une image a partir d'une Mysql database [ par ilyazi ]
je suis un etudiant debutant en php et je suis bloque sur un bout de code pour mon projet de fin d'annee. En voici deux fichiers que j'ai creer pour e
Super débutant MSQLi [ par ydu ]
Bonjour tout le monde,Avant tout je tiens a vous préciser, je suis un SD "Super Débutant". En effet, je me suis fourni PHP & Mysql pour les nuls.M
|
Derniers Blogs
GESTION D'EXCEPTION AVEC LES TASKSGESTION D'EXCEPTION AVEC LES TASKS par richardc
Nous avons vu dans un précédent article comment utiliser Task pour effectuer des opérations dans un autre thread.
Malheureusement, comme tout le monde n'est pas parfait, il se peut que cette exécution se passe mal et qu'une exception se produise.
La...
Cliquez pour lire la suite de l'article par richardc DéMARRONS AVEC LES TASKSDéMARRONS AVEC LES TASKS par richardc
Que vous le vouliez ou non, le développement multi-tâche est maintenant une obligation pour toute nouvelle application. Il est donc vital d'en comprendre les mécanismes et de s'y mettre le plus tôt possible.
En attendant le .NET Framework 4.5 avec le...
Cliquez pour lire la suite de l'article par richardc SLIDE & DéMO TECHDAYS 2012 - FAST & FURIOUS XAML APPSSLIDE & DéMO TECHDAYS 2012 - FAST & FURIOUS XAML APPS par Vko
Retrouvez les slides et les démo de ma session Fast & Furious XAML Apps. A ceux qui se posent la question : "est-ce que le code de la DataGrid est disponible?", je vous répondrais "pas encore". Je vais mettre en place un projet codeplex pour part...
Cliquez pour lire la suite de l'article par Vko XNA IS DEAD!XNA IS DEAD! par richardc
Depuis la semaine dernière (et grâce aux TechDays 2012), je me penche activement sur la nouvelle version de Windows, aka Windows 8. Vous me direz, il était temps puisque la première preview date de Septembre dernier.
OK. Remarquez, on n'en est qu'aux...
Cliquez pour lire la suite de l'article par richardc TECHDAYS PARIS 2012 : WINDOWS SERVER "8" QUOI DE 9 !TECHDAYS PARIS 2012 : WINDOWS SERVER "8" QUOI DE 9 ! par ROMELARD Fabrice
Speakers: Fabrice Meillon et Stanislas Quastana Cette session est basée entièrement sur celle donnée lors de la BUILD cet hiver. Il n'y a pas d'ajout d'information en rapport avec cet évènement passé. Windows 8 Server sera intégralem...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DocTranslate (V3.1.0.0)DOCTRANSLATE (V3.1.0.0)DocTranslate est un traducteur de document Microsoft Word, PowerPoint et Excel. Il permet d'autom... Cliquez pour télécharger DocTranslate Tribler (2012)TRIBLER (2012)Tribler est un client pair à pair (P2P/Peer-to-Peer) open source avec la capacité de regarder des... Cliquez pour télécharger Tribler OneSwarm (2012)ONESWARM (2012)Le peer-to-peer qui protège votre vie privée, c'est OneSwarm.
Ce logiciel de peer-to-peer crypté... Cliquez pour télécharger OneSwarm PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System
|