Accueil > > > CLASSE BASE DE DONNEES , EX AVEC MYSQL & MSSQL [PHP5 & PHP4]
CLASSE BASE DE DONNEES , EX AVEC MYSQL & MSSQL [PHP5 & PHP4]
Information sur la source
Description
Bonjour tout le monde :-) Voici une petite classe d'abstraction de base de données. 1 classe parente, database, gère tout le travail. J'ai joint 2 classes héritant de cette classe parente : - 1 pour mysql - 1 pour mssql Vous verrez qu'elles sont toutes les 2 TRES simples. Je n'ai pas implémenté d'autres bdd, mais peut-être un jour... Ce code est disponible en 2 versions : 1 version PHP5, et 1 version PHP4. Et il est livré avec 2 fichiers de tests, 1 pour chaque version de PHP. C'est une classe volontairement allégée, donnant accès à ce que l'on utilise le plus souvent, simplement, pas de frioritures...mis à part 2 ou 3 petits trucs ;-) Possibilités : - connexion (ouais ouais) explicite ou non - déconnexion (si si) explicite (ou non...) - sélection de base explicite (ou non... ;-) ) - méthode pour lancer une requête (bah oui) - num_rows : compte le nombre de lignes renvoyées par une requête - fetch row : va chercher les résultats sous forme d'un tableau indexé numériquement - fetch_array : bla bla indexé numériquement ET associativement - fetch_assoc : bla bla indexé associativement - error : méthode privé pour gérer (et afficher si on veut) les erreurs. Et les stocker. - get : méthode pour afficher une ou plusieurs propriétés de l'instance - queryPerf : lance une requête, ET fait un bench dessus. Et l'affiche. Et le stocke. Voili voulou, c'est tout :-) Je balance le code pour la version PHP5 ici (mais dans le zip, y a tout, php4 et php5)
Source
- // FICHIER database.cls.php
-
- <?php
- class database {
-
- /***************************************************************************************************************************************
- * Définition des Propriétés
- ***************************************************************************************************************************************/
- protected $config = array ();
- private $errorLog = array ();
- private $options = array (
- 'ERROR_DISPLAY' => true
- );
- protected $sql = '';
- private $qryRes;
- protected $link;
- private $sQueryPerf = array ();
-
- /***************************************************************************************************************************************
- * Constructeur
- * On peut ou non passer le nom de la base de données; si on le passe, la connexion à la base se fait d'elle même
- * Sinon, il faudra passer par la méthode select_base ()
- * @Param string $host => serveur de bdd
- * @Param string $user => login
- * @Param string $pwd => password
- * @Param string $db => base de donnée
- * @Param array $options => options (voir la propriété $config)
- ***************************************************************************************************************************************/
- public function __construct ($host, $user, $pwd, $db = '', $options = array ()) {
- $this -> config['HOST'] = $host;
- $this -> config['USER'] = $user;
- $this -> config['PWD'] = $pwd;
- if (!empty ($options)) {
- foreach ($options as $clef => $opt) {
- if (array_key_exists ($clef, $this -> options) && is_bool ($opt)) {
- $this -> options[$clef] = $opt;
- }
- }
- }
- if (!empty ($db)) {
- $this -> connect ();
- $this -> select_base ($db);
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode de connexion
- * méthode publique
- * Se fait automatiquement, ou peut être explicitement appelée
- ***************************************************************************************************************************************/
- public function connect () {
- if (false === $this -> private_connect ()) {
- $this -> error (get_class ($this).' :: connect()', $this -> private_errno().' : '.$this -> private_error(), 'Connexion avec Host : '.$this -> config['HOST'].' User : '. $this -> config['USER'].' Pwd : ********');
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode de log des erreurs
- * méthode privée
- * @Param string $func => méthode appelant l'erreur
- * @Param string $err => message d'erreur interne au moteur de la bdd
- * @Param string $qry => requête ayant provquée l'erreur, ou message interne à la classe
- ***************************************************************************************************************************************/
- private function error ($func, $err, $qry) {
- $this -> errorLog[] = $func.' : '.$err.' => '.$qry;
- if ($this -> options['ERROR_DISPLAY'] === true) {
- echo 'ERREUR! : ', $this -> errorLog[key ($this -> errorLog)], '<br />';
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode de sélection d'une base de données
- * méthode publique
- * @Param string $name => nom de la base.
- ***************************************************************************************************************************************/
- public function select_base($name=null) {
- if (false === is_scalar ($name)) {
- $this -> error (get_class ($this).' :: select_base()', $this -> private_errno().' : '.$this -> private_error(), 'Nom incorrect passé à la méthode : '.$name);
- } else {
- $this -> config['BD'] = $name;
- if (false === $this -> private_select_base()) {
- $this -> error (get_class ($this).' :: select_base()', $this -> private_errno().' : '.$this -> private_error(), 'La méthode n\'a pu se connecter à la base : '.$name);
- }
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode de fermeture de la connexion
- * méthode publique
- ***************************************************************************************************************************************/
- public function close() {
- $this -> __destruct ();
- }
-
- /***************************************************************************************************************************************
- * Destructeur
- * méthode publique
- ***************************************************************************************************************************************/
- public function __destruct () {
- if (isset($this-> link) ) {
- $this -> private_close();
- unset ($this-> link);
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode de "requêtage"
- * méthode publique
- * @Param string $qry => requête
- ***************************************************************************************************************************************/
- public function query ($qry) {
- $this -> sql = $qry;
- if (false === $this -> qryRes = $this -> private_query ()) {
- $this -> error (get_class ($this).' :: query ()', $this -> private_errno ().' : '.$this -> private_error (), $this -> sql);
- } else {
- return $this -> qryRes;
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode pour compter le nombre de lignes renvoyées
- * méthode publique
- * @Param mixed $qry => ressource d'une requête ou identifiant de ressource pour mssql
- * On peut la passer explicitement, ou prendre la propriété
- ***************************************************************************************************************************************/
- public function num_rows ($qry = null) {
- if ((get_class ($this) === 'mysql' && is_resource ($qry)) || (get_class ($this) === 'mssql' && is_int ($qry))) {
- $num = $this -> private_num_rows ($qry);
- if (false === $num) {
- $this -> error (get_class ($this).' :: num_rows ()', $this -> private_errno ().' : '.$this -> private_error (), $this -> sql);
- return false;
- } else {
- return $num;
- }
- }elseif (isset ($this -> qryRes) && (get_class ($this) === 'mysql' && is_resource ($this -> qryRes)) || (get_class ($this) === 'mssql' && is_int ($this -> qryRes))) {
- $num = $this -> private_num_rows ($this -> qryRes);
- if (false === $num) {
- $this -> error (get_class ($this).' :: num_rows ()', $this -> private_errno ().' : '.$this -> private_error (), $this -> sql);
- return false;
- } else {
- return $num;
- }
- } else {
- $this -> error (get_class ($this).' :: num_rows ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de ressource valide');
- }
- }
- /***************************************************************************************************************************************
- * Méthode pour parcourir les lignes renvoyée par ujne requête sous forme de tableau associatif
- * méthode publique
- * @Param mixed $qry => ressource d'une requête ou identifiant de ressource pour mssql
- * On peut la passer explicitement, ou prendre la propriété
- ***************************************************************************************************************************************/
- public function fetch_assoc ($qry = null) {
- if ((get_class ($this) === 'mysql' && is_resource ($qry)) || (get_class ($this) === 'mssql' && is_int ($qry))) {
- return $this -> private_fetch_assoc ($qry);
- }elseif (isset ($this -> qryRes) && (get_class ($this) === 'mysql' && is_resource ($this -> qryRes)) || (get_class ($this) === 'mssql' && is_int ($this -> qryRes))) {
- return $this -> private_fetch_assoc ($this -> qryRes);
- } else {
- $this -> error (get_class ($this).' :: fetch_assoc ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de ressource valide');
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode pour parcourir les lignes renvoyée par ujne requête sous forme de tableau associatif et numérique
- * méthode publique
- * @Param mixed $qry => ressource d'une requête ou identifiant de ressource pour mssql
- * On peut la passer explicitement, ou prendre la propriété
- ***************************************************************************************************************************************/
- public function fetch_array ($qry = null) {
- if ((get_class ($this) === 'mysql' && is_resource ($qry)) || (get_class ($this) === 'mssql' && is_int ($qry))) {
- return $this -> private_fetch_array ($qry);
- }elseif (isset ($this -> qryRes) && (get_class ($this) === 'mysql' && is_resource ($this -> qryRes)) || (get_class ($this) === 'mssql' && is_int ($this -> qryRes))) {
- return $this -> private_fetch_array ($this -> qryRes);
- } else {
- $this -> error (get_class ($this).' :: fetch_array ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de ressource valide');
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode pour parcourir les lignes renvoyée par ujne requête sous forme de tableau numérique
- * méthode publique
- * @Param mixed $qry => ressource d'une requête ou identifiant de ressource pour mssql
- * On peut la passer explicitement, ou prendre la propriété
- ***************************************************************************************************************************************/
- public function fetch_row ($qry = null) {
- if ((get_class ($this) === 'mysql' && is_resource ($qry)) || (get_class ($this) === 'mssql' && is_int ($qry))) {
- return $this -> private_fetch_row ($qry);
- }elseif (isset ($this -> qryRes) && (get_class ($this) === 'mysql' && is_resource ($this -> qryRes)) || (get_class ($this) === 'mssql' && is_int ($this -> qryRes))) {
- return $this -> private_fetch_row ($this -> qryRes);
- } else {
- $this -> error (get_class ($this).' :: fetch_row ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de ressource valide');
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode renvoyant le dernier ID inséré
- * méthode publique
- ***************************************************************************************************************************************/
- public function insert_id () {
- if (isset ($this -> link)) {
- $id = $this -> private_insert_id ();
- } else {
- $this -> error (get_class ($this).' :: insert_id ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de lien valide');
- return false;
- }
- if (false === $id) {
- $this -> error (get_class ($this).' :: insert_id ()', $this -> private_errno ().' : '.$this -> private_error (), 'Echec de récupération du dernier id inséré');
- return false;
- } else {
- return $id;
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode pour récupérer la valeur d'une ou plusieurs propriété(s) de la classe
- * méthode publique
- * On peut passer n'importe quel nombre de paramètres, sous la forme de chaînes ayant pour valeur le nom d'une
- * propriété EXISTANTE de la classe
- ***************************************************************************************************************************************/
- public function get () {
- $aArgs = func_get_args();
- foreach ($aArgs as $clef => $arg) {
- if (isset ($this -> $arg)) {
- $aRetour[$arg] = $this -> $arg;
- }
- }
- if (isset ($aRetour) && is_array ($aRetour)) {
- return $aRetour;
- } else {
- return false;
- }
- }
-
- /***************************************************************************************************************************************
- * Méthode de "requêtage" renvoyant en plus les performances de la requête (bench)
- * méthode publique
- * @Param string $qry => requête
- ***************************************************************************************************************************************/
- public function queryPerf ($qry) {
- $this -> sql = $qry;
- $start = microtime ();
- $this -> qryRes = $this -> private_query ();
- $stop = microtime ();
- if (false === $this -> qryRes) {
- $this -> error (get_class ($this).' :: query ()', $this -> private_errno ().' : '.$this -> private_error (), $this -> sql);
- return false;
- } else {
- $elapsed = $stop - $start;
- $clef = count ($this -> sQueryPerf);
- $this -> sQueryPerf[$clef]['query'] = $this -> sql;
- $this -> sQueryPerf[$clef]['time'] = $elapsed;
- echo 'Query [', $this -> sQueryPerf[$clef]['query'], '] => ', $this -> sQueryPerf[$clef]['time'];
- return $this -> qryRes;
- }
- }
- }
- ?>
-
- //FICHIER mssql.cls.php
-
- <?php
- class mssql extends database {
-
- protected function private_connect () {
- if (false === $this -> link = @mssql_connect ($this -> config['HOST'], $this -> config['USER'], $this -> config['PWD'])) {
- return false;
- } else {
- return true;
- }
- }
-
- protected function private_select_base () {
- if (false === @mssql_select_db($this->config['BD'], $this->link)) {
- return false;
- } else {
- return true;
- }
- }
-
- protected function private_close() {
- mssql_close($this-> link);
- }
-
-
- protected function private_query () {
- return @mssql_query ($this -> sql, $this -> link);
- }
-
- protected function private_num_rows ($qry) {
- return @mssql_num_rows ($qry);
- }
-
- protected function private_fetch_row ($qry) {
- return @mssql_fetch_row ($qry);
- }
-
- protected function private_fetch_array ($qry) {
- return @mssql_fetch_array ($qry);
- }
-
- protected function private_fetch_assoc ($qry) {
- return @mssql_fetch_array ($qry);
- }
-
- protected function private_insert_id () {
- $sQuery = 'SELECT @@IDENTITY';
- $requete = $this -> query ($sQuery);
- $res = $this -> fetch_row ($requete);
- return $res[0];
- }
-
- protected function private_errno () {
- return false;
- }
-
- protected function private_error () {
- return @mssql_get_last_message ();
- }
- }
- ?>
-
- // FICHIER mysql.cls.php
-
- <?php
- class mysql extends database {
-
- protected function private_connect () {
- if (false === $this -> link = @mysql_connect ($this -> config['HOST'], $this -> config['USER'], $this -> config['PWD'])) {
- return false;
- } else {
- return true;
- }
- }
-
- protected function private_select_base () {
- if (false === @mysql_select_db($this->config['BD'], $this->link)) {
- return false;
- } else {
- return true;
- }
- }
-
- protected function private_close() {
- mysql_close($this-> link);
- }
-
-
- protected function private_query () {
- return @mysql_query ($this -> sql, $this -> link);
- }
-
- protected function private_num_rows ($qry) {
- return @mysql_num_rows ($qry);
- }
-
- protected function private_fetch_assoc ($qry) {
- return @mysql_fetch_assoc ($qry);
- }
-
- protected function private_fetch_array ($qry) {
- return @mysql_fetch_array ($qry);
- }
-
- protected function private_fetch_row ($qry) {
- return @mysql_fetch_row ($qry);
- }
-
- protected function private_insert_id () {
- return @mysql_insert_id ($this -> link);
- }
-
- protected function private_errno () {
- return @mysql_errno ($this -> link);
- }
-
- protected function private_error () {
- return @mysql_error ($this -> link);
- }
- }
- ?>
-
- // FICHIER EXEMPLE (non exhaustif, loin de là...) test.php
-
- <?php
- DEFINE ('SQL_LOGIN', '');
- DEFINE ('SQL_PWD', '');
- DEFINE ('SQL_DB', '');
- DEFINE ('SQL_HOST', '');
-
- $dbOptions = array (
- 'ERROR_DISPLAY' => true
- );
-
- function __autoload ($class_name) {
- require_once $class_name . '.cls.php';
- }
-
- $oDB = new mysql (SQL_HOST, SQL_LOGIN, SQL_PWD, SQL_DB, $dbOptions);
-
- $sQuery = 'select * from users';
- $oDB -> queryPerf ($sQuery);
-
- echo '<br />';
-
- $sQuery = 'select * from departements';
- $oDB -> queryPerf ($sQuery);
-
- echo '<br />';
-
- $arr = $oDB -> get ('link', 'config', 'sQueryPerf');
- echo '<pre>', print_r ($arr), '</pre>';
-
- $sQuery = '
- SELECT
- mag.mag_id, mag.mag_libelle, dept.dept_libelle
- FROM
- magasins mag, departements dept
- WHERE
- mag.dept_id = dept.dept_id
- ORDER BY
- mag.dept_id, mag.mag_libelle
- ';
- $oDB -> connect ();
- $requete = $oDB -> query ($sQuery);
- $oDB -> close (); // pour mysql, je le fais ici
- $deptPrev = '';
- $sForm = '';
- while ($mag = $oDB -> fetch_assoc ($requete)) {
- if ($deptPrev !== $mag['dept_libelle']) {
- if (!empty ($deptPrev)) {
- $sForm .= '<optgroup />';
- }
- $deptPrev = $mag['dept_libelle'];
- $sForm .= '<optgroup label="'.$mag['dept_libelle'].'">';
- }
- $selected = (isset ($_POST['mag_id']) && $_POST['mag_id'] === $mag['mag_id'])?'selected="selected"':'';
- $sForm .= '<option value="'.$mag['mag_id'].'" '.$selected.'>'.$mag['mag_libelle'].'</option>';
- }
- $oDB -> close (); // pour mssql, je le fais ici...saleté de mssql, hein ? ;-)
- ?>
// FICHIER database.cls.php
<?php
class database {
/***************************************************************************************************************************************
* Définition des Propriétés
***************************************************************************************************************************************/
protected $config = array ();
private $errorLog = array ();
private $options = array (
'ERROR_DISPLAY' => true
);
protected $sql = '';
private $qryRes;
protected $link;
private $sQueryPerf = array ();
/***************************************************************************************************************************************
* Constructeur
* On peut ou non passer le nom de la base de données; si on le passe, la connexion à la base se fait d'elle même
* Sinon, il faudra passer par la méthode select_base ()
* @Param string $host => serveur de bdd
* @Param string $user => login
* @Param string $pwd => password
* @Param string $db => base de donnée
* @Param array $options => options (voir la propriété $config)
***************************************************************************************************************************************/
public function __construct ($host, $user, $pwd, $db = '', $options = array ()) {
$this -> config['HOST'] = $host;
$this -> config['USER'] = $user;
$this -> config['PWD'] = $pwd;
if (!empty ($options)) {
foreach ($options as $clef => $opt) {
if (array_key_exists ($clef, $this -> options) && is_bool ($opt)) {
$this -> options[$clef] = $opt;
}
}
}
if (!empty ($db)) {
$this -> connect ();
$this -> select_base ($db);
}
}
/***************************************************************************************************************************************
* Méthode de connexion
* méthode publique
* Se fait automatiquement, ou peut être explicitement appelée
***************************************************************************************************************************************/
public function connect () {
if (false === $this -> private_connect ()) {
$this -> error (get_class ($this).' :: connect()', $this -> private_errno().' : '.$this -> private_error(), 'Connexion avec Host : '.$this -> config['HOST'].' User : '. $this -> config['USER'].' Pwd : ********');
}
}
/***************************************************************************************************************************************
* Méthode de log des erreurs
* méthode privée
* @Param string $func => méthode appelant l'erreur
* @Param string $err => message d'erreur interne au moteur de la bdd
* @Param string $qry => requête ayant provquée l'erreur, ou message interne à la classe
***************************************************************************************************************************************/
private function error ($func, $err, $qry) {
$this -> errorLog[] = $func.' : '.$err.' => '.$qry;
if ($this -> options['ERROR_DISPLAY'] === true) {
echo 'ERREUR! : ', $this -> errorLog[key ($this -> errorLog)], '<br />';
}
}
/***************************************************************************************************************************************
* Méthode de sélection d'une base de données
* méthode publique
* @Param string $name => nom de la base.
***************************************************************************************************************************************/
public function select_base($name=null) {
if (false === is_scalar ($name)) {
$this -> error (get_class ($this).' :: select_base()', $this -> private_errno().' : '.$this -> private_error(), 'Nom incorrect passé à la méthode : '.$name);
} else {
$this -> config['BD'] = $name;
if (false === $this -> private_select_base()) {
$this -> error (get_class ($this).' :: select_base()', $this -> private_errno().' : '.$this -> private_error(), 'La méthode n\'a pu se connecter à la base : '.$name);
}
}
}
/***************************************************************************************************************************************
* Méthode de fermeture de la connexion
* méthode publique
***************************************************************************************************************************************/
public function close() {
$this -> __destruct ();
}
/***************************************************************************************************************************************
* Destructeur
* méthode publique
***************************************************************************************************************************************/
public function __destruct () {
if (isset($this-> link) ) {
$this -> private_close();
unset ($this-> link);
}
}
/***************************************************************************************************************************************
* Méthode de "requêtage"
* méthode publique
* @Param string $qry => requête
***************************************************************************************************************************************/
public function query ($qry) {
$this -> sql = $qry;
if (false === $this -> qryRes = $this -> private_query ()) {
$this -> error (get_class ($this).' :: query ()', $this -> private_errno ().' : '.$this -> private_error (), $this -> sql);
} else {
return $this -> qryRes;
}
}
/***************************************************************************************************************************************
* Méthode pour compter le nombre de lignes renvoyées
* méthode publique
* @Param mixed $qry => ressource d'une requête ou identifiant de ressource pour mssql
* On peut la passer explicitement, ou prendre la propriété
***************************************************************************************************************************************/
public function num_rows ($qry = null) {
if ((get_class ($this) === 'mysql' && is_resource ($qry)) || (get_class ($this) === 'mssql' && is_int ($qry))) {
$num = $this -> private_num_rows ($qry);
if (false === $num) {
$this -> error (get_class ($this).' :: num_rows ()', $this -> private_errno ().' : '.$this -> private_error (), $this -> sql);
return false;
} else {
return $num;
}
}elseif (isset ($this -> qryRes) && (get_class ($this) === 'mysql' && is_resource ($this -> qryRes)) || (get_class ($this) === 'mssql' && is_int ($this -> qryRes))) {
$num = $this -> private_num_rows ($this -> qryRes);
if (false === $num) {
$this -> error (get_class ($this).' :: num_rows ()', $this -> private_errno ().' : '.$this -> private_error (), $this -> sql);
return false;
} else {
return $num;
}
} else {
$this -> error (get_class ($this).' :: num_rows ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de ressource valide');
}
}
/***************************************************************************************************************************************
* Méthode pour parcourir les lignes renvoyée par ujne requête sous forme de tableau associatif
* méthode publique
* @Param mixed $qry => ressource d'une requête ou identifiant de ressource pour mssql
* On peut la passer explicitement, ou prendre la propriété
***************************************************************************************************************************************/
public function fetch_assoc ($qry = null) {
if ((get_class ($this) === 'mysql' && is_resource ($qry)) || (get_class ($this) === 'mssql' && is_int ($qry))) {
return $this -> private_fetch_assoc ($qry);
}elseif (isset ($this -> qryRes) && (get_class ($this) === 'mysql' && is_resource ($this -> qryRes)) || (get_class ($this) === 'mssql' && is_int ($this -> qryRes))) {
return $this -> private_fetch_assoc ($this -> qryRes);
} else {
$this -> error (get_class ($this).' :: fetch_assoc ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de ressource valide');
}
}
/***************************************************************************************************************************************
* Méthode pour parcourir les lignes renvoyée par ujne requête sous forme de tableau associatif et numérique
* méthode publique
* @Param mixed $qry => ressource d'une requête ou identifiant de ressource pour mssql
* On peut la passer explicitement, ou prendre la propriété
***************************************************************************************************************************************/
public function fetch_array ($qry = null) {
if ((get_class ($this) === 'mysql' && is_resource ($qry)) || (get_class ($this) === 'mssql' && is_int ($qry))) {
return $this -> private_fetch_array ($qry);
}elseif (isset ($this -> qryRes) && (get_class ($this) === 'mysql' && is_resource ($this -> qryRes)) || (get_class ($this) === 'mssql' && is_int ($this -> qryRes))) {
return $this -> private_fetch_array ($this -> qryRes);
} else {
$this -> error (get_class ($this).' :: fetch_array ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de ressource valide');
}
}
/***************************************************************************************************************************************
* Méthode pour parcourir les lignes renvoyée par ujne requête sous forme de tableau numérique
* méthode publique
* @Param mixed $qry => ressource d'une requête ou identifiant de ressource pour mssql
* On peut la passer explicitement, ou prendre la propriété
***************************************************************************************************************************************/
public function fetch_row ($qry = null) {
if ((get_class ($this) === 'mysql' && is_resource ($qry)) || (get_class ($this) === 'mssql' && is_int ($qry))) {
return $this -> private_fetch_row ($qry);
}elseif (isset ($this -> qryRes) && (get_class ($this) === 'mysql' && is_resource ($this -> qryRes)) || (get_class ($this) === 'mssql' && is_int ($this -> qryRes))) {
return $this -> private_fetch_row ($this -> qryRes);
} else {
$this -> error (get_class ($this).' :: fetch_row ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de ressource valide');
}
}
/***************************************************************************************************************************************
* Méthode renvoyant le dernier ID inséré
* méthode publique
***************************************************************************************************************************************/
public function insert_id () {
if (isset ($this -> link)) {
$id = $this -> private_insert_id ();
} else {
$this -> error (get_class ($this).' :: insert_id ()', $this -> private_errno ().' : '.$this -> private_error (), 'Pas de lien valide');
return false;
}
if (false === $id) {
$this -> error (get_class ($this).' :: insert_id ()', $this -> private_errno ().' : '.$this -> private_error (), 'Echec de récupération du dernier id inséré');
return false;
} else {
return $id;
}
}
/***************************************************************************************************************************************
* Méthode pour récupérer la valeur d'une ou plusieurs propriété(s) de la classe
* méthode publique
* On peut passer n'importe quel nombre de paramètres, sous la forme de chaînes ayant pour valeur le nom d'une
* propriété EXISTANTE de la classe
***************************************************************************************************************************************/
public function get () {
$aArgs = func_get_args();
foreach ($aArgs as $clef => $arg) {
if (isset ($this -> $arg)) {
$aRetour[$arg] = $this -> $arg;
}
}
if (isset ($aRetour) && is_array ($aRetour)) {
return $aRetour;
} else {
return false;
}
}
/***************************************************************************************************************************************
* Méthode de "requêtage" renvoyant en plus les performances de la requête (bench)
* méthode publique
* @Param string $qry => requête
***************************************************************************************************************************************/
public function queryPerf ($qry) {
$this -> sql = $qry;
$start = microtime ();
$this -> qryRes = $this -> private_query ();
$stop = microtime ();
if (false === $this -> qryRes) {
$this -> error (get_class ($this).' :: query ()', $this -> private_errno ().' : '.$this -> private_error (), $this -> sql);
return false;
} else {
$elapsed = $stop - $start;
$clef = count ($this -> sQueryPerf);
$this -> sQueryPerf[$clef]['query'] = $this -> sql;
$this -> sQueryPerf[$clef]['time'] = $elapsed;
echo 'Query [', $this -> sQueryPerf[$clef]['query'], '] => ', $this -> sQueryPerf[$clef]['time'];
return $this -> qryRes;
}
}
}
?>
//FICHIER mssql.cls.php
<?php
class mssql extends database {
protected function private_connect () {
if (false === $this -> link = @mssql_connect ($this -> config['HOST'], $this -> config['USER'], $this -> config['PWD'])) {
return false;
} else {
return true;
}
}
protected function private_select_base () {
if (false === @mssql_select_db($this->config['BD'], $this->link)) {
return false;
} else {
return true;
}
}
protected function private_close() {
mssql_close($this-> link);
}
protected function private_query () {
return @mssql_query ($this -> sql, $this -> link);
}
protected function private_num_rows ($qry) {
return @mssql_num_rows ($qry);
}
protected function private_fetch_row ($qry) {
return @mssql_fetch_row ($qry);
}
protected function private_fetch_array ($qry) {
return @mssql_fetch_array ($qry);
}
protected function private_fetch_assoc ($qry) {
return @mssql_fetch_array ($qry);
}
protected function private_insert_id () {
$sQuery = 'SELECT @@IDENTITY';
$requete = $this -> query ($sQuery);
$res = $this -> fetch_row ($requete);
return $res[0];
}
protected function private_errno () {
return false;
}
protected function private_error () {
return @mssql_get_last_message ();
}
}
?>
// FICHIER mysql.cls.php
<?php
class mysql extends database {
protected function private_connect () {
if (false === $this -> link = @mysql_connect ($this -> config['HOST'], $this -> config['USER'], $this -> config['PWD'])) {
return false;
} else {
return true;
}
}
protected function private_select_base () {
if (false === @mysql_select_db($this->config['BD'], $this->link)) {
return false;
} else {
return true;
}
}
protected function private_close() {
mysql_close($this-> link);
}
protected function private_query () {
return @mysql_query ($this -> sql, $this -> link);
}
protected function private_num_rows ($qry) {
return @mysql_num_rows ($qry);
}
protected function private_fetch_assoc ($qry) {
return @mysql_fetch_assoc ($qry);
}
protected function private_fetch_array ($qry) {
return @mysql_fetch_array ($qry);
}
protected function private_fetch_row ($qry) {
return @mysql_fetch_row ($qry);
}
protected function private_insert_id () {
return @mysql_insert_id ($this -> link);
}
protected function private_errno () {
return @mysql_errno ($this -> link);
}
protected function private_error () {
return @mysql_error ($this -> link);
}
}
?>
// FICHIER EXEMPLE (non exhaustif, loin de là...) test.php
<?php
DEFINE ('SQL_LOGIN', '');
DEFINE ('SQL_PWD', '');
DEFINE ('SQL_DB', '');
DEFINE ('SQL_HOST', '');
$dbOptions = array (
'ERROR_DISPLAY' => true
);
function __autoload ($class_name) {
require_once $class_name . '.cls.php';
}
$oDB = new mysql (SQL_HOST, SQL_LOGIN, SQL_PWD, SQL_DB, $dbOptions);
$sQuery = 'select * from users';
$oDB -> queryPerf ($sQuery);
echo '<br />';
$sQuery = 'select * from departements';
$oDB -> queryPerf ($sQuery);
echo '<br />';
$arr = $oDB -> get ('link', 'config', 'sQueryPerf');
echo '<pre>', print_r ($arr), '</pre>';
$sQuery = '
SELECT
mag.mag_id, mag.mag_libelle, dept.dept_libelle
FROM
magasins mag, departements dept
WHERE
mag.dept_id = dept.dept_id
ORDER BY
mag.dept_id, mag.mag_libelle
';
$oDB -> connect ();
$requete = $oDB -> query ($sQuery);
$oDB -> close (); // pour mysql, je le fais ici
$deptPrev = '';
$sForm = '';
while ($mag = $oDB -> fetch_assoc ($requete)) {
if ($deptPrev !== $mag['dept_libelle']) {
if (!empty ($deptPrev)) {
$sForm .= '<optgroup />';
}
$deptPrev = $mag['dept_libelle'];
$sForm .= '<optgroup label="'.$mag['dept_libelle'].'">';
}
$selected = (isset ($_POST['mag_id']) && $_POST['mag_id'] === $mag['mag_id'])?'selected="selected"':'';
$sForm .= '<option value="'.$mag['mag_id'].'" '.$selected.'>'.$mag['mag_libelle'].'</option>';
}
$oDB -> close (); // pour mssql, je le fais ici...saleté de mssql, hein ? ;-)
?>
Conclusion
Merci à FhX pour quelques idées piquées à sa classe d'abstraction à lui, plus complète.
Historique
- 20 janvier 2006 17:44:56 :
- Rajout du test sur le type des valeurs des options, dans l'instanciation de la classe.
- 20 janvier 2006 18:00:59 :
- Oublis de 'return' ;-)
- 08 février 2006 12:59:31 :
- Correction sur la méthode num_rows ().
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
MySQL [ par intello2001 ]
j'ai fait une base MySQL toute neuve, toute VIDE !!je voudrai avoir des exemple de création de table et tt sa...je c juste sa :$host="sql.free.fr";$ba
BDD mysql --> Access [ par YarbY ]
SalutJ'ai un site qui tourne avec une base de donées mysql, et je voudrais récupérer les données dans Access, en gardant ma base sur le serveur. Je ve
postgresl --> mysql [ par NDK ]
Bonjour, Je dois reprendre un site qui a été réalisé en php avec une bdd en Postgresql, et j'aimerais convertire le code pour qu il travaille avec une
Php & MySql ??? [ par nova85 ]
Je voudrai savoir si il est possible de realiser un site assez important juste avec une BDD mysql , si c'est capable de resister , et surtout savoir s
classe PHP pour accés BDD [ par cuicui ]
Bonjour,Je recherche des classes en PHP qui perùet d'acceder à des des bases de données tel que INTERBASE ou MySQL.Merci à touscuicui...
image php Mysql [ par arnaldo21 ]
bonjour pourriez-vous me donner un exemple concret d'affichage d'image a partir d'une bdd. J'utilise un upload qui stock le nom de l'image dans la bdd
Problème affichage BD multiples [ par ekipage2 ]
Bonjour,j'ai plusieurs BD : eleve / matières / et exercicesLorque l'élèv se connecte, il peut afficher la liste des exercices correspondants à sa clas
Intégrité BDD [ par isis26 ]
Bonjour,Je suis débutante en PHP. Je dois charger un fichier texte dans une base de données MySQL.Une ligne du fichier permet de remplir plu
Mettre un log et psw sur bdd mysql ??? [ par nova85 ]
Comment met ton un login et un mot de passe sur une base mysql avec phpmyadmin ?nova
liste deroulante bdd mysql [ par lagombe ]
Voilà je tente désespérement de monter sur un formulaire deux listes déroulantes, la première apparaît toute seule (contenu d'une bdd, ça ça marche...
|
Derniers Blogs
IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc REACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITERREACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITER par Groc
Une mauvaise utilisation de rx lors de l'écriture d'une couche d'accès à des services peut conduire à des cas embarassants avec des erreurs mal gérées, des appels qui ne partent lorsqu'ils le devraient, et même des résultats incorrects . le tout nuis...
Cliquez pour lire la suite de l'article par Groc SHAREPOINT BLOG SITE, PROBLèME D'ARCHIVESSHAREPOINT BLOG SITE, PROBLèME D'ARCHIVES par junarnoalg
Dernièrement, nous avons migré le site
myTIC
vers un nouveau serveur SharePoint 2010. Dans les contenus que nous vouloins récupérer, nous avions un certain nombre de blogs.
Nous avons utilisé les commandes Power...
Cliquez pour lire la suite de l'article par junarnoalg
Forum
GOOGLE MAPGOOGLE MAP par fatmanajjar
Cliquez pour lire la suite par fatmanajjar
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|