begin process at 2012 02 11 02:39:39
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Class et Objet ( POO )

 > CLASSE OBJET DAO COUCHE D'ACCÈS À MYSQL DATA ACCESS OBJECT

CLASSE OBJET DAO COUCHE D'ACCÈS À MYSQL DATA ACCESS OBJECT


 Information sur la source

Note :
1 / 10 - par 1 personne
1,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Class et Objet ( POO ) Classé sous :dao, mysql, class, classe, layer Niveau :Initié Date de création :24/06/2006 Vu :10 211

Auteur : djroulo

Ecrire un message privé
Site perso
Commentaire sur cette source (2)
Ajouter un commentaire et/ou une note

 Description

/*
------------DAO------------
----DataAcessObject ------
EN fait, c'est une layer au-dessus de MySQL

Ne marche que si ta connexion à Mysql a déjà été activée !!!!
mon conseil : fait 2 fichiers :
    - req_connect.php // connecte à la BD MySQL
    - req_disconnect.php // mysql_free = libère la connexion

Comment marche la classe DAO ?
Exemple concret :
*/

include_once("class.dao.php4");

$dao_object = new DAO(); // instancie le nouvel object dao_object de type DAO
$query = "SELECT * FROM table WHERE id=1";
$dao_object->DAO_query($query); // lance la requete et récupère le résultat
$dao_object->DAO_numrows(); // nombre d'enregistrements retournés

// requête UPDATE INSERT
$query = "INSERT INTO table (col1, col2) VALUES (1,'text')";
$dao_object->DAO_execute($query); // unbuffered query = sans retour de ligne
$dao_object->DAO_affrows(); // number of affected rows pour les requêtes UPDATE / INSERT / DELETE / DROP

pour afficher, 3 possibilité comme mysql :
while($val = $dao_object->DAO_fetch_object())
{
    echo $val->id;
}

while($val = $dao_object->DAO_fetch_array())
{
    echo $val["col1"]; // le nom de la colonne
    // ou encore :
    echo $val[0]; // le numéro de la colonne en commançant par zéro
}


while($val = $dao_object->DAO_fetch_assoc())
{
    echo $val["col2"]; // le nom de la colonne seulement
}

/*
Attention, si tu as un object $this->dao_object dans une de tes classes,
et qui tu t'en sers dans plusieurs méthodes, tu vas avoir un conflit entre les 2 méthodes.
Il faut donc instancier un objet par boucle while, exemple :
*/

while($val1 = $dao_object1->DAO_fetch_assoc())
{
    while($val2 = $dao_object2->DAO_fetch_object())
    {
       echo $val1["col1"] . " is not equal to " . $val2["col1"];
    }
}

Source

  • <?php
  • /**
  • * class DAO
  • * DataAccessObject
  • * @version 0.1
  • * @copyright 2006
  • */
  • class DAO{
  • var $dao_query = NULL;
  • var $dao_result = NULL;
  • var $badquery = NULL;
  • /**
  • * Throws an error
  • * @param : nothing, uses the last query
  • * @return : die and display the error message
  • */
  • function DAO_error(){
  • $this->badquery = "Erreur dans la req&ecirc;te.";
  • die($this->badquery . ":" . $this->dao_query . "<br />" . mysql_error());
  • }
  • /**
  • * Sets the query and sends the query to recover a result
  • * @param : all SQL query types (SELECT, INSERT, UPDATE ...)
  • * @return : nothing, sets the query and resultset
  • */
  • function DAO_query($dao_query){
  • $this->dao_query = $dao_query;
  • $this->dao_result = mysql_query($dao_query) or $this->DAO_error();
  • }
  • /**
  • * Sets the query and sends the query to recover a result
  • * For UPDATE, INSERT, DELETE operations
  • * @param : a SQL query (UPDATE, INSERT, DELETE)
  • * @return : nothing, sets the query and resultset without waiting
  • */
  • function DAO_execute($dao_query){
  • $this->dao_query = $dao_query;
  • $this->dao_result = mysql_unbuffered_query($dao_query) or $this->DAO_error();
  • }
  • /**
  • * Retruns the number of rows returns by the last query
  • * @param : nothing
  • * @return : the number of rows returned in the the last resultset
  • * For SELECT queries
  • */
  • function DAO_numrows(){
  • $dao_numrows = mysql_num_rows($this->dao_result);
  • return $dao_numrows;
  • }
  • /**
  • * Returns the number of affected rows in the last operation
  • * @param : nothing
  • * @return : the number of rows affected by the last UPDATE, INSERT, DELETE query
  • */
  • function DAO_affrows(){
  • $dao_affrows = mysql_affected_rows();
  • return $dao_affrows;
  • }
  • /**
  • * Returns the number of fields returned by the last request
  • * @param : nothing
  • * @return : the number of fields contened if the last resultset
  • */
  • function DAO_num_fields(){
  • $dao_num_fields = mysql_num_fields($this->dao_result);
  • return $dao_num_fields;
  • }
  • /**
  • * Returns the field name of the field
  • * @param : indice of the field in the query
  • * @return : the name of the field at the $indice position
  • */
  • function DAO_field_name($indice){
  • $dao_field_name = mysql_field_name($this->dao_result,$indice);
  • return $dao_field_name;
  • }
  • /**
  • * Returns an object containing the fields of the query
  • * @param : nothing takes the last resultset
  • * @return : an object accessible with the query fields
  • */
  • function DAO_fetch_object(){
  • $dao_object = mysql_fetch_object($this->dao_result); //or die($bad_query);
  • return $dao_object;
  • }
  • /**
  • * Return an associative array only
  • * @param : nothing, takes the last resutset
  • * @return : an associative array
  • */
  • function DAO_fetch_assoc(){
  • $dao_assoc = mysql_fetch_assoc($this->dao_result);
  • return $dao_assoc;
  • }
  • /**
  • * Returns a mixed array
  • * @param : nothing, takes the last resutset
  • * @return : a mixed array
  • */
  • function DAO_fetch_array(){
  • $dao_array = mysql_fetch_array($this->dao_result);
  • return $dao_array;
  • }
  • /**
  • * Returns the last auto_increment id
  • * @param : the identifier and the table name
  • * @return : the last auto_increment id
  • */
  • function DAO_last_id($id,$table){
  • $li=mysql_query("SELECT $id FROM $table ORDER BY $id DESC LIMIT 0,1");
  • $r=mysql_fetch_assoc($li);
  • if (mysql_num_rows($li)==1) {
  • return $r[$id];
  • }else{
  • return NULL;
  • }
  • }
  • /**
  • * Save the transaction at the name given in parameter
  • * @param : the SAVEPOINT name
  • * @return : nothing, sets the query and resultset
  • */
  • function DAO_savepoint($dao_savepoint){
  • $this->dao_query="SAVEPOINT $dao_savepoint";
  • $this->dao_result=mysql_unbuffered_query($this->dao_query) or $this->DAO_error();
  • }
  • /**
  • * Starts a transaction
  • * @param : nothing, takes the last resutset
  • * @return : nothing, sets the resultset
  • */
  • function DAO_start_transaction(){
  • $this->dao_query = "START TRANSACTION;";
  • $this->dao_result=mysql_unbuffered_query($this->dao_query) or $this->DAO_error();
  • $this->dao_query = "SET AUTOCOMMIT=0;";
  • $this->dao_result=mysql_unbuffered_query($this->dao_query) or $this->DAO_error();
  • }
  • /**
  • * Perform a COMMIT to the database
  • * @param: nothing
  • * @return : nothing, sets the query and resultset
  • */
  • function DAO_commit(){
  • $this->dao_query = "COMMIT";
  • $this->dao_result = mysql_unbuffered_query("COMMIT") or $this->DAO_error();
  • }
  • /**
  • * Rollback To Savepoint
  • * @param : the SAVEPOINT
  • * @return : nothing, sets the query and resultset
  • */
  • function DAO_r2s($dao_savepoint){
  • $this->dao_query = "ROLLBACK TO $dao_savepoint";
  • $this->dao_result = mysql_unbuffered_query("ROLLBACK TO $dao_savepoint") or $this->DAO_error();
  • }
  • /**
  • * Rollback to the last transaction started
  • * @param : nothing
  • * @return : nothing, sets the query and resultset
  • */
  • function DAO_rollback(){
  • $this->dao_query = "ROLLBACK";
  • $this->dao_result = mysql_unbuffered_query("ROLLBACK") or $this->DAO_error();
  • }
  • }
  • ?>
<?php
/**
 * class DAO
 * DataAccessObject
 * @version 0.1
 * @copyright 2006
 */
class DAO{
	var $dao_query = NULL;
	var $dao_result = NULL;
	var $badquery = NULL;

	/**
	* Throws an error
	* @param : nothing, uses the last query
	* @return : die and display the error message
	*/
	function DAO_error(){
		$this->badquery = "Erreur dans la req&ecirc;te.";
		die($this->badquery . ":" . $this->dao_query . "<br />" . mysql_error());
	}
	/**
	* Sets the query and sends the query to recover a result
	* @param : all SQL query types (SELECT, INSERT, UPDATE ...)
	* @return : nothing, sets the query and resultset
	*/
	function DAO_query($dao_query){
		$this->dao_query = $dao_query;
		$this->dao_result = mysql_query($dao_query) or $this->DAO_error();
	}
	/**
	* Sets the query and sends the query to recover a result
	* For UPDATE, INSERT, DELETE operations
	* @param : a SQL query (UPDATE, INSERT, DELETE)
	* @return : nothing, sets the query and resultset without waiting
	*/
	function DAO_execute($dao_query){
		$this->dao_query = $dao_query;
		$this->dao_result = mysql_unbuffered_query($dao_query) or $this->DAO_error();
	}
	/**
	* Retruns the number of rows returns by the last query
	* @param : nothing
	* @return : the number of rows returned in the the last resultset
	* For SELECT queries
	*/
	function DAO_numrows(){
		$dao_numrows = mysql_num_rows($this->dao_result);
		return $dao_numrows;
	}
	/**
	* Returns the number of affected rows in the last operation
	* @param : nothing
	* @return : the number of rows affected by the last UPDATE, INSERT, DELETE query
	*/
	function DAO_affrows(){
		$dao_affrows = mysql_affected_rows();
		return $dao_affrows;
	}
	/**
	* Returns the number of fields returned by the last request
	* @param : nothing
	* @return : the number of fields contened if the last resultset
	*/
	function DAO_num_fields(){
		$dao_num_fields = mysql_num_fields($this->dao_result);
		return $dao_num_fields;
	}
	/**
	* Returns the field name of the field
	* @param : indice of the field in the query
	* @return : the name of the field at the $indice position
	*/
	function DAO_field_name($indice){
		$dao_field_name = mysql_field_name($this->dao_result,$indice);
		return $dao_field_name;
	}
	/**
	* Returns an object containing the fields of the query
	* @param : nothing takes the last resultset
	* @return : an object accessible with the query fields
	*/
	function DAO_fetch_object(){
		$dao_object = mysql_fetch_object($this->dao_result); //or die($bad_query);
		return $dao_object;
	}
	/**
	* Return an associative array only
	* @param : nothing, takes the last resutset
	* @return : an associative array
	*/
	function DAO_fetch_assoc(){
		$dao_assoc = mysql_fetch_assoc($this->dao_result);
		return $dao_assoc;
	}
	/**
	* Returns a mixed array
	* @param : nothing, takes the last resutset
	* @return : a mixed array
	*/
	function DAO_fetch_array(){
		$dao_array = mysql_fetch_array($this->dao_result);
		return $dao_array;
	}
	/**
	* Returns the last auto_increment id
	* @param : the identifier and the table name
	* @return : the last auto_increment id
	*/
	function DAO_last_id($id,$table){
		$li=mysql_query("SELECT $id FROM $table ORDER BY $id DESC LIMIT 0,1");
		$r=mysql_fetch_assoc($li);
		if (mysql_num_rows($li)==1) {
			return $r[$id];
		}else{
			return NULL;
		}
	}
	/**
	* Save the transaction at the name given in parameter
	* @param : the SAVEPOINT name
	* @return : nothing, sets the query and resultset
	*/
	function DAO_savepoint($dao_savepoint){
		$this->dao_query="SAVEPOINT $dao_savepoint";
		$this->dao_result=mysql_unbuffered_query($this->dao_query) or $this->DAO_error();
	}
	/**
	* Starts a transaction
	* @param : nothing, takes the last resutset
	* @return : nothing, sets the resultset
	*/
	function DAO_start_transaction(){
		$this->dao_query = "START TRANSACTION;";
		$this->dao_result=mysql_unbuffered_query($this->dao_query) or $this->DAO_error();
		$this->dao_query = "SET AUTOCOMMIT=0;";
		$this->dao_result=mysql_unbuffered_query($this->dao_query) or $this->DAO_error();
	}
	/**
	* Perform a COMMIT to the database
	* @param: nothing
	* @return : nothing, sets the query and resultset
	*/
	function DAO_commit(){
		$this->dao_query = "COMMIT";
		$this->dao_result = mysql_unbuffered_query("COMMIT") or $this->DAO_error();
	}
	/**
	* Rollback To Savepoint
	* @param : the SAVEPOINT
	* @return : nothing, sets the query and resultset
	*/
	function DAO_r2s($dao_savepoint){
		$this->dao_query = "ROLLBACK TO $dao_savepoint";
		$this->dao_result = mysql_unbuffered_query("ROLLBACK TO $dao_savepoint") or $this->DAO_error();
	}
	/**
	* Rollback to the last transaction started
	* @param : nothing
	* @return : nothing, sets the query and resultset
	*/
	function DAO_rollback(){
		$this->dao_query = "ROLLBACK";
		$this->dao_result = mysql_unbuffered_query("ROLLBACK") or $this->DAO_error();
	}
}
?>



 Sources du même auteur

Source avec Zip Source avec une capture LOGGER LE TEMPS D'EXÉCUTION DE VOS FONCTIONS PHP
Source avec Zip Source avec une capture GÉNÉRATION DE CLASSES D'ACCÈS AUX DONNÉES À PARTIR DES TABLE...
GÉNÉRATION DE FORMULAIRES XHTML
Source avec Zip Source avec une capture CALENDRIER DE SAISIE PHP ET JAVASCRIPT

 Sources de la même categorie

CLASSE DE GESTION DE "VARIABLES GLOBALES D'ENVIRONNEMENT" par pifou25
Source avec Zip COLLECTION.CLASS.MIN.PHP par thunderhunter
Source avec Zip SIMPLETEMPLATE par thunderhunter
Source avec Zip Source avec une capture VOIR QUI VISITE VOTRE SITE par Dariumis
Source avec Zip CLASS SIMPLE CBASEDONNEE par smag42

 Sources en rapport avec celle ci

Source avec Zip CLASS MYSQL 5/PHP5 AVEC GESTION DES EXCEPTION ET DES REQUÊTE... par devil_may_cry
CLASSE MYSQL UTILISANT LES FONCTIONS PDO par Vince66
Source avec Zip CLASSE SQL par benjycorp
Source avec Zip Source avec une capture GÉNÉRATION DE CLASSES D'ACCÈS AUX DONNÉES À PARTIR DES TABLE... par djroulo
CLASSE DATABASE POUR CONNECTION ET MODIFICATION D'UNE BDD MY... par franco_se

Commentaires et avis

Commentaire de kankrelune le 25/06/2006 17:03:39

[quote]Ne marche que si ta connexion à Mysql a déjà été activée !!!![/quote]

Pourquoi ne pas avoir fait une méthode d'ouverture de connection avec stockage du pointeur en interne... et une de fermeture pourrait être utile aussi... .. .


function DAO_numrows()
{
    $dao_numrows = mysql_num_rows($this->dao_result);
    return $dao_numrows;
}

... .. .

function DAO_numrows()
{
    return mysql_num_rows($this->dao_result);
}

non... .. ?

Le die dans la méthode d'erreur n'est pas une bonne idée... en prod c'est crade d'afficher une page blanche ou partiellement chargée avec un erreur sql... qui plus est si tu veux gérer différament les erreurs (les loguer par exemple) t'es bonbon... .. .

/**
* Returns the last auto_increment id
* @param : the identifier and the table name
* @return : the last auto_increment id
*/
function DAO_last_id($id,$table)
{
   $li=mysql_query("SELECT $id FROM $table ORDER BY $id DESC LIMIT 0,1");
   $r=mysql_fetch_assoc($li);
   if (mysql_num_rows($li)==1) {
       return $r[$id];
   }else{
       return NULL;
   }
}

... .. .

function DAO_last_id()
{
   return mysql_insert_id();
}

Une méthode escape() ne serait pas du luxe... du genre...

function escape($value)
{
   if (get_magic_quotes_gpc())
     $value = stripslashes($value);
  
   if (!is_numeric($value))
     $value = mysql_real_escape_string($value);

   return $value;
}

@ tchaOo°

Commentaire de Antidote le 26/06/2006 15:05:05

Salut,

Perso je ne vois l'intéret d'une telle classe. Tu ne fais que masquer les fonctions mysql de php par les tiennes sans véritable ajout de fonctionnalité.

Tu n'utilises pas le pointer sur la resource mysql comme précisé par KANKRELUNE, voir tu te complexifie la vie notemment avec le last id, sache qu'un fonction mysql eiste déjà pour ceci.

Comme tu le dis tu rajoutes une couche de fonction non seulement inutile mais en plus ça ralentie ton code pour rien et je trouve le rend plus floue, besoin d'appeler une classe, un fichier de connexion un fichier de déconnexion alors que tout existe sans cela.

Je tiens à précisé qu'aucune configuration n'est possible comme le choix d'avoir unne connexion persistante, une connexion unique, une connexion pour chaque instance de la classe, la façon dont pourrait être géré les erreurs, la gestion de la connexion et de la déconnexion est inexistante...

Encore ta couche permettrais de faire l'abstraction du moteur de BDD utilisé ça serait utilise si on n'avais plus à se soucier qu'on utilise les fonction Mysql, Mysqli, Db2, Oracle, postgreSql etc ...

Petite précision faire une requête Sql dans le but de faire un mysql_num_rows est très lent et totalement inutile sachant qu'il existe une fonction COUNT() dans le langage Sql qui s'avère être bien plus rapide.

Mon commentaire final serait que cette classe est inadaptée et inutile et n'est pas du tout d'un niveau initié je trouve.

PS : j'aprécie l'effort d'écriture à la PEAR.

Note : 1 pour l'effort d'écriture.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

fatal error sur chargement de class [ par fabrice_pi ] salut à tous,j'utilise une classe PHP pour faire mes taleaux en html. depuis peu j'ai l'erreur suivante :Fatal error: Cannot instantiate non-existent 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 Recherche mysql [ par simon0000 ] salut tous le monde ,j'ai une table mysql nom&#233;&nbsp;ecole ou il ya Récupérer un tableau d'une bdd [ par Leneuf8000 ] Rebonjour, j'ai enregistr&#233; dans ma base des tableaux dans une table, ce tableau contient des valeurs qui doivent &#234;tre mises &#224; jour chaq Formulaire avec select et update de bdd mysql [ par arnold002 ] Bonjour &#224; tous,J'ai un formulaire qui contient 2 champs de type select : classe et annee.Je veux associer chaque classe &#224; chaque ann&#233;e passage de variables de form vers bdd mysql [ par arnold002 ] Bonjour,Mon probl&#232;me n'avance pas...Mon form contient 2 champs select for($i<FONT color=#008000 s Retour des données d'une classe MySQL [ par Jerem_ ] Salut, Depuis ce matin, j'asseye de coter une classe MySQL pour mon site. La classe marche tr&#232;s bien quand je fait une requete INSERT, etc .. M Visibilité des membres d'une classe avec autoload ? [ par petitelarve ] Bonjour, ca m'&#233;n&#233;rve !!! J'ai une classe que je veut instancier dans un autre script avec autoload. L'objectif &#233;tant de r&#233;cup&#233 Problème de code [ par stu76 ] Bonjour tout le monde ,Voil&#224; je planche sur un programme scolaire et j'ai un gros prob, je travaille sur un programme qui utilise trois base de d Bug dans une double liste [ par stu76 ] Bonjour, Malalam m'a donné des infos hier sur les doubles liste, et je le remercie car ca ma été super utile. J'ai presque résolu le prob sauf que je


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2012
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
272829    

Consulter la suite du CalendriCode

Photothèque

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,858 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales