Vous êtes ici Codes PHP et MySQL > Classes > Classe d'abstraction PHP4 de base de données,...

 

Classe d'abstraction PHP4 de base de données, mysql et mssql

Classe d'abstraction de base de données PHP4, mysql et mssql. On peut facilement y ajouter une nouvelle interface pour une autre base de données; Johan Barbier vous offre ici les exemples mysql et mssql
La classe database gèrant le reste.
Elle possède les fonctions de base (query, connect, select_base, num_rows, fetch_rows, fetch_array, fetch_assoc), une gestion des erreurs avec un log d'erreurs, et une méthode de bench des requêtes (queryPerf) effectuée (à n'utiliser que pour du debug, donc pas en production, mais en développement).
Un exemple de test est effectué tout en bas du script.
 
Johan Barbier
[4] sources en PHP voir
Code vu 10423 fois
Enregistré le 14 Fév 2006
  • Digg ce code sur digg.com
  • Bookmark ce code sur del.icio.us
  • Bookmark ce code sur Google
  • Bookmark ce code sur Yahoo
  • Ajoute Classe d'abstraction PHP4 de base de données, mysql et mssql
  • Partage ce code sur Facebook
 
 
 
 

Code Source


01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
419.
420.
421.
422.
423.
424.
425.
426.
427.
428.
429.
430.
431.
432.
433.
434.
435.
436.
437.
438.
439.
440.
441.
442.
443.
444.
445.
446.
447.
448.
449.
450.
451.
452.
453.
454.
455.
456.
457.
458.
459.
460.
461.
462.
463.
464.
465.
466.
467.
468.
469.
470.
471.
472.
473.
474.
475.
476.
477.
478.
479.
480.
481.
482.
483.
484.
485.
486.
487.
488.
489.
490.
491.
492.
493.
494.
495.
496.
497.
498.
499.
500.
501.
502.
503.
504.
505.
506.
507.
508.
509.
510.
511.
512.
513.
514.
515.
516.
517.
518.
519.
520.
 
<?php
/******************************************************************************/
/*                                                                            */
/*                       __        ____                                       */
/*                 ___  / /  ___  / __/__  __ _____________ ___               */
/*                / _ \/ _ \/ _ \_\ \/ _ \/ // / __/ __/ -_|_-<               */
/*               / .__/_//_/ .__/___/\___/\_,_/_/  \__/\__/___/               */
/*              /_/       /_/                                                 */
/*                                                                            */
/*                                                                            */
/******************************************************************************/
/*                                                                            */
/* Titre          : Classe d'abstraction PHP4 de base de données, mysql et... */
/*                                                                            */
/* URL            : http://www.phpsources.org/scripts158-PHP.htm              */
/* Auteur         : Johan Barbier                                             */
/* Date édition   : 14 Fév 2006                                               */
/*                                                                            */
/******************************************************************************/

class database {

    /*********************************************************************
    * Définition des Propriétés
    *********************************************************************/
    var $config = array ();
    var $errorLog '';
    var $options = array (
        'ERROR_DISPLAY' => true
        );
    var $sql '';
    var $qryRes;
    var $link;
    var $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)
    *********************************************************************/
    function database ($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
    *********************************************************************/
    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
    *********************************************************************/
    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.
    *********************************************************************/
    function select_base($name) {
        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
    *********************************************************************/
    function close() {
        if (isset($this-> link) ) {
            $this -> private_close();
            unset ($this-> link);
        }
    }

    /*********************************************************************
    * Méthode de "requêtage"
    * méthode publique
    * @Param string $qry => requête
    *********************************************************************/
    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é
    *********************************************************************/
     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é
    *********************************************************************/
    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 ou 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é
    *********************************************************************/
    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é
    *********************************************************************/
    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
    *********************************************************************/
    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
    *********************************************************************/
    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
    *********************************************************************/
    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'], '<br />';
            return $this -> qryRes;
        }
    }
}
?>

<?php
class mssql extends database {

    function private_connect () {
        if (false === $this -> link = @mssql_connect ($this -> config['HOST'],
                      $this -> config['USER'], $this -> config['PWD'])) {
            return false;
        } else {
            return true;
        }
    }

    function private_select_base () {
         if (false === @mssql_select_db($this->config['BD'], $this->link)) {
            return false;
         } else {
            return true;
         }
    }

    function private_close() {
        mssql_close($this-> link);
    }


    function private_query () {
        return @mssql_query ($this -> sql$this -> link);
    }

    function private_num_rows ($qry) {
        return @mssql_num_rows ($qry);
    }

    function private_fetch_row ($qry) {
        return @mssql_fetch_row ($qry);
    }

    function private_fetch_array ($qry) {
        return @mssql_fetch_array ($qry);
    }

    function private_fetch_assoc ($qry) {
        return @mssql_fetch_array ($qry);
    }

    function private_insert_id () {
        $sQuery 'SELECT @@IDENTITY';
        $requete $this -> query ($sQuery);
        $res $this -> fetch_row ($requete);
        return $res[0];
    }

    function private_errno () {
        return false;
    }

    function private_error () {
        return @mssql_get_last_message ();
    }
}
?>

<?php
class mysql extends database {

    function private_connect () {
        if (false === $this -> link = @mysql_connect ($this -> config['HOST'],
                      $this -> config['USER'],
                      $this -> config['PWD'])) {
            return false;
        } else {
            return true;
        }
    }

    function private_select_base () {
         if (false === @mysql_select_db($this->config['BD'], $this->link)) {
            return false;
         } else {
            return true;
         }
    }

    function private_close() {
        mysql_close($this-> link);
    }


    function private_query () {
        return @mysql_query ($this -> sql$this -> link);
    }

    function private_num_rows ($qry) {
        return @mysql_num_rows ($qry);
    }

    function private_fetch_assoc ($qry) {
        return @mysql_fetch_assoc ($qry);
    }

    function private_fetch_array ($qry) {
        return @mysql_fetch_array ($qry);
    }

    function private_fetch_row ($qry) {
        return @mysql_fetch_row ($qry);
    }

    function private_insert_id () {
        return @mysql_insert_id ($this -> link);
    }

    function private_errno () {
        return @mysql_errno ($this -> link);
    }

    function private_error () {
        return @mysql_error ($this -> link);
    }
}


/*********************************************************************
    * TEST TEST TEST
    *********************************************************************/

DEFINE ('SQL_LOGIN',    '');
DEFINE ('SQL_PWD',  '');
DEFINE ('SQL_DB',       '');
DEFINE ('SQL_HOST',     '');

$dbOptions = array (
    'ERROR_DISPLAY' => true
    );

$oDB = new mysql (SQL_HOSTSQL_LOGIN,  SQL_PWDSQL_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''errorLog');
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);
$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 ();
?>


 

Fonctions du code

: Crée un tableau - (PHP 4, PHP 5)
: Détermine si une variable contient une valeur non nulle - (PHP 4, PHP 5)
: Vérifie si une clé existe dans un tableau - (PHP 4 >= 4.0.7, PHP 5)
: - (PHP 4, PHP 5)
: Retourne la classe d'un objet - (PHP 4, PHP 5)
: Affiche une chaîne de caractères - (PHP 4, PHP 5)
: Retourne une clé d'un tableau associatif - (PHP 4, PHP 5)
: - (PHP 4 >= 4.0.5, PHP 5)
: Détermine si une variable est affectée - (PHP 4, PHP 5)
: Détruit une variable - (PHP 4, PHP 5)
: - (PHP 4, PHP 5)
: Détermine si une variable est de type nombre entier - (PHP 4, PHP 5)
: Retourne les arguments d'une fonction sous la forme d'un tableau - (PHP 4,...
: Détermine si une variable est un tableau - (PHP 4, PHP 5)
: Retourne le timestamp UNIX actuel avec les microsecondes - (PHP 4, PHP 5)
: Compte le nombre d'éléments d'un tableau ou le nombre de propriétés...
: Ouvre une connexion à un serveur MS SQL server - (PHP 4, PHP 5, PECL...
: Sélectionne la base de données MS SQL - (PHP 4, PHP 5, PECL odbtp:1.1.1-1.1.4)
: Ferme une connexion MS SQL Server - (PHP 4, PHP 5, PECL odbtp:1.1.1-1.1.4)
: Envoie une requête SQL au serveur MS SQL - (PHP 4, PHP 5, PECL odbtp:1.1.1-1.1.4)
: Retourne le nombre de lignes dans un résultat MS SQL - (PHP 4, PHP 5, PECL...
: Lit une ligne de résultat MS SQL dans un tableau numérique - (PHP 4, PHP 5, PECL...
: Lit une ligne de résultat MS SQL dans un tableau - (PHP 4, PHP 5, PECL...
: Retourne le dernier message d'erreur du serveur - (PHP 4, PHP 5, PECL...
: Ouvre une connexion à un serveur MySQL - (PHP 4, PHP 5, PECL mysql:1.0)
: Sélectionne une base de données MySQL - (PHP 4, PHP 5, PECL mysql:1.0)
: Ferme la connexion MySQL - (PHP 4, PHP 5, PECL mysql:1.0)
: Envoie une requête à un serveur MySQL - (PHP 4, PHP 5, PECL mysql:1.0)
: Retourne le nombre de lignes d'un résultat MySQL - (PHP 4, PHP 5, PECL...
: Lit une ligne de résultat MySQL dans un tableau associatif - (PHP 4 >= 4.0.3, PHP...
: - (PHP 4, PHP 5, PECL mysql:1.0)
: Retourne une ligne de résultat MySQL sous la forme d'un tableau - (PHP 4, PHP 5,...
: - (PHP 4, PHP 5, PECL mysql:1.0)
: Retourne le numéro d'erreur de la dernière commande MySQL - (PHP 4, PHP 5, PECL...
: - (PHP 4, PHP 5, PECL mysql:1.0)
: Définit une constante - (PHP 4, PHP 5)
: Affiche des informations lisibles pour une variable - (PHP 4, PHP 5)
Ajouter un commentaire
Code de sécurité

Attention: Les champs marqués d'une étoile * sont obligatoires
 
Librairie PHP

Connexion

 
 

Classes

 
 

PHP

 
 
 
 
    Offres d'emploi

Plus de 500 offres d'emploi PHP/MySQL

Offres d'emploi
 
    Editeur PHP
 
        Publicité