Fork me on GitHub






Methode pour inserer des données dans la base
Aspirant
Inscrit: 05/07/2003 12:24
Messages: 73
Bonjour,

Je m'essaye à la création de module et j'aurais une question :

Quelle est la meilleur methode pour inserer des données dans mysql ?

Par exemple j'ai ceci comme code dans un fichier php :

$sqlinsert 'INSERT INTO '.$xoopsDB->prefix('tsd4xoops_server_config').' (configid, serverip,serverudpport,serverqueryport,serverforbiddennicknamechars,serverlimitchannel,serverautorefresh,serverpassword,serveradmintsport,serverstatus) VALUES ('.$configid.', '.$xoopsDB->quoteString($serverip).', '.$xoopsDB->quoteString($serverudpport).', '.$xoopsDB->quoteString($serverqueryport).', '.$xoopsDB->quoteString($serverforbiddennicknamechars).','.$xoopsDB->quoteString($serverlimitchannel).','.$xoopsDB->quoteString($serverautorefresh).','.$xoopsDB->quoteString($serverpassword).','.$xoopsDB->quoteString($serveradmintsport).','.$xoopsDB->quoteString($serverstatus).')';


Et la question est comment faire pour lui dire d'ingurgiter les données sans retaper a chaque fois les differents champs de la table par exemple ?

Merci d'avance de vos lumières .

Edit : dans le cas ou j'ai un formulaire avec 50 000 champs a recup bien sur car pour 2~3 champs c'est pas interessant.

Posté le : 09/06/2006 19:05
Partager Twitter Partagez cette article sur GG+
Re: Methode pour inserer des données dans la base
Semi pro
Inscrit: 06/01/2004 09:37
De Non loin de Paris
Messages: 666
Salut,

Le mieux est d'utiliser le model objet de XOOPS. Il faut que tu separe tes données sous forme d'objet, ainsi, chaque formulaire correspond à la modification d'une classe d'objet. Ainsi, je ne pense pas que tu te retrouva avec un formaulaire de 50000 champs
Si tu veut plus de renseignements sur le model objet de XOOPS, n'hésite pas

A+

Posté le : 09/06/2006 19:52
Partager Twitter Partagez cette article sur GG+
Re: Methode pour inserer des données dans la base
Aspirant
Inscrit: 05/07/2003 12:24
Messages: 73
Bonsoir zoullou,

Tu penses à cette methode la ? => Creation de formulaire sur Documentation Xoops.

Le soucis c'est que j'ai commencé à m'inspirer du module tinycontent (qui dates un peux) j'aurais du prevoir (oups.

Si tu as des astuces pour creer des formulaires (edition,update,suppression) je suis preneur. La j'ai terminé ma bdd, j'avais commencé à faire mes outils pour automatiser les requetes sous openoffice, mais bon autant qu'a faire partir sur de bonne base.

J'ai regarder ton module, mais bon faut avoué que je suis une mobilette en php/mysql. Je débute (lentement )

En tout cas merci de ton aide précieuse (et de ton module extcal :merci:).

Bonne soirée.

Posté le : 09/06/2006 20:55
Partager Twitter Partagez cette article sur GG+
Re: Methode pour inserer des données dans la base
Semi pro
Inscrit: 06/01/2004 09:37
De Non loin de Paris
Messages: 666
Je ne prétend pas que ma methode est la meilleur mais elle me convient . Voici un exemple basé sur un module que je suis en train de créer. Cet exemple ne concerne que la classe permettant de gérer les catégories.

1- Il faut créer ta base de donné en pensant à tout les champs nécessaires. Il faut essayé de ne pas en oublier au début car sinon c'est un peut galère d'en rajouter. Jusque là rien de bien difficile.

CREATE TABLE `extgallery_cat` (
  `
cat_idint(11NOT NULL auto_increment,
  `
cat_pidint(11NOT NULL,
  `
cat_limit_infint(11NOT NULL,
  `
cat_limit_supint(11NOT NULL,
  `
cat_levelint(11NOT NULL,
  `
cat_namevarchar(255NOT NULL,
  `
cat_desctext NOT NULL,
  `
cat_nb_albumint(11NOT NULL default '0',
  `
cat_nb_photoint(11NOT NULL default '0',
  `
cat_dateint(11NOT NULL,
  `
photo_idint(11NOT NULL default '0',
  `
uidint(11NOT NULL,
  
PRIMARY KEY  (`cat_id`)
COMMENT='eXtGallery By Zoullou (www.Zoullou.info)' AUTO_INCREMENT=;


2- Ensuite je me sert d'une classe créer par Mithrandir pour XOOPS 2.2 : PersistableObjectHandler que je rennome afin qu'il n'y ai pas de problemes si plusieurs module l'utilise. J'ai rajouté quelques méthodes comme celle pour obtenir la valeur max d'une colonne ou pour incrémenté un compteur. Désolé pour la longueur, mais vous ferez le trie . Voici son contenu :
class ExtgalleryPersistableObjectHandler extends XoopsObjectHandler {

    
/**#@+
    * Information about the class, the handler is managing
    *
    * @var string
    */
    
var $table;
    var 
$keyName;
    var 
$className;
    var 
$identifierName;
    
/**#@-*/

    /**
    * Constructor - called from child classes
    * @param object     $db         {@link XoopsDatabase} object
    * @param string     $tablename  Name of database table
    * @param string     $classname  Name of Class, this handler is managing
    * @param string     $keyname    Name of the property, holding the key
    *
    * @return void
    */
    
function ExtgalleryPersistableObjectHandler(&$db$tablename$classname$keyname$idenfierName false) {
        
$this->XoopsObjectHandler($db);
        
$this->table $db->prefix($tablename);
        
$this->keyName $keyname;
        
$this->className $classname;
        if (
$idenfierName != false) {
            
$this->identifierName $idenfierName;
        }
    }

    
/**
     * create a new user
     * 
     * @param bool $isNew Flag the new objects as "new"?
     *
     * @return object
     */
    
function &create($isNew true) {
        
$obj =& new $this->className();
        if (
$isNew === true) {
            
$obj->setNew();
        }
        return 
$obj;
    }

    
/**
     * retrieve an object
     * 
     * @param mixed $id ID of the object - or array of ids for joint keys. Joint keys MUST be given in the same order as in the constructor
     * @param bool $as_object whether to return an object or an array
     * @return mixed reference to the object, FALSE if failed
     */
    
function &get($id$as_object true) {
        if (
is_array($this->keyName)) {
            
$criteria = new CriteriaCompo();
            for (
$i 0$i count($this->keyName); $i++) {
                
$criteria->add(new Criteria($this->keyName[$i], intval($id[$i])));
            }
        }
        else {
            
$criteria = new Criteria($this->keyNameintval($id));
        }
        
$criteria->setLimit(1);
        
$obj_array $this->getObjects($criteriafalse$as_object);
        if (
count($obj_array) != 1) {
            return 
$this->create();
        }
        return 
$obj_array[0];
    }

    
/**
     * retrieve objects from the database
     * 
     * @param object $criteria {@link CriteriaElement} conditions to be met
     * @param bool $id_as_key use the ID as key for the array?
     * @param bool $as_object return an array of objects?
     *
     * @return array
     */
    
function &getObjects($criteria null$id_as_key false$as_object true)
    {
        
$ret = array();
        
$limit $start 0;
        
$sql 'SELECT * FROM '.$this->table;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            
$sql .= ' '.$criteria->renderWhere();
            if (
$criteria->getSort() != '') {
                
$sql .= ' ORDER BY '.$criteria->getSort().' '.$criteria->getOrder();
            }
            
$limit $criteria->getLimit();
            
$start $criteria->getStart();
        }
        
$result $this->db->query($sql$limit$start);
        if (!
$result) {
            return 
$ret;
        }

        
$ret $this->convertResultSet($result$id_as_key$as_object);
        return 
$ret;
    }

    
/**
     * Convert a database resultset to a returnable array
     *
     * @param object $result database resultset
     * @param bool $id_as_key - should NOT be used with joint keys
     * @param bool $as_object
     *
     * @return array
     */
    
function convertResultSet($result$id_as_key false$as_object true) {
        
$ret = array();
        while (
$myrow $this->db->fetchArray($result)) {
            
$obj =& $this->create(false);
            
$obj->assignVars($myrow);
            if (!
$id_as_key) {
                if (
$as_object) {
                    
$ret[] =& $obj;
                }
                else {
                    
$row = array();
                    
$vars $obj->getVars();
                    foreach (
array_keys($vars) as $i) {
                        
$row[$i] = $obj->getVar($i);
                    }
                    
$ret[] = $row;
                }
            } else {
                if (
$as_object) {
                    
$ret[$myrow[$this->keyName]] =& $obj;
                }
                else {
                    
$row = array();
                    
$vars $obj->getVars();
                    foreach (
array_keys($vars) as $i) {
                        
$row[$i] = $obj->getVar($i);
                    }
                    
$ret[$myrow[$this->keyName]] = $row;
                }
            }
            unset(
$obj);
        }

        return 
$ret;
    }

    
/**
    * Retrieve a list of objects as arrays - DON'T USE WITH JOINT KEYS
    *
    * @param object $criteria {@link CriteriaElement} conditions to be met
    * @param int   $limit      Max number of objects to fetch
    * @param int   $start      Which record to start at
    *
    * @return array
    */
    
function getList($criteria null$limit 0$start 0) {
        
$ret = array();
        if (
$criteria == null) {
            
$criteria = new CriteriaCompo();
        }
        
        if (
$criteria->getSort() == '') {
            
$criteria->setSort($this->identifierName);
        }
            
        
$sql 'SELECT '.$this->keyName;
        if(!empty(
$this->identifierName)){
            
$sql .= ', '.$this->identifierName;
        }
        
$sql .= ' FROM '.$this->table;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            
$sql .= ' '.$criteria->renderWhere();
            if (
$criteria->getSort() != '') {
                
$sql .= ' ORDER BY '.$criteria->getSort().' '.$criteria->getOrder();
            }
            
$limit $criteria->getLimit();
            
$start $criteria->getStart();
        }
        
$result $this->db->query($sql$limit$start);
        if (!
$result) {
            return 
$ret;
        }

        
$myts =& MyTextSanitizer::getInstance();
        while (
$myrow $this->db->fetchArray($result)) {
            
//identifiers should be textboxes, so sanitize them like that
            
$ret[$myrow[$this->keyName]] = empty($this->identifierName)?1:$myts->htmlSpecialChars($myrow[$this->identifierName]);
        }
        return 
$ret;
    }

    
/**

     * count objects matching a condition
     * 
     * @param object $criteria {@link CriteriaElement} to match
     * @return int count of objects
     */
    
function getCount($criteria null)
    {
        
$field "";
        
$groupby false;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            if (
$criteria->groupby != "") {
                
$groupby true;
                
$field $criteria->groupby.", "//Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
            
}
        }
        
$sql 'SELECT '.$field.'COUNT(*) FROM '.$this->table;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            
$sql .= ' '.$criteria->renderWhere();
            if (
$criteria->groupby != "") {
                
$sql .= $criteria->getGroupby();
            }
        }
        
$result $this->db->query($sql);
        if (!
$result) {
            return 
0;
        }
        if (
$groupby == false) {
            list(
$count) = $this->db->fetchRow($result);
            return 
$count;
        }
        else {
            
$ret = array();
            while (list(
$id$count) = $this->db->fetchRow($result)) {
                
$ret[$id] = $count;
            }
            return 
$ret;
        }
    }

    
/**
     * delete an object from the database
     * 
     * @param mixed $id id of the object to delete
     * @param bool $force
     * @return bool FALSE if failed.
     */
    
function delete($id$force false)
    {
        if (
is_array($this->keyName)) {
            
$clause = array();
            for (
$i 0$i count($this->keyName); $i++) {
                
$clause[] = $this->keyName[$i]." = ".$id[$i];
            }
            
$whereclause implode(" AND "$clause);
        }
        else {
            
$whereclause $this->keyName." = ".$id;
        }
        
$sql "DELETE FROM ".$this->table." WHERE ".$whereclause;
        if (
false != $force) {
            
$result $this->db->queryF($sql);
        } else {
            
$result $this->db->query($sql);
        }
        if (!
$result) {
            return 
false;
        }
        return 
true;
    }

    
/**
     * insert a new object in the database
     * 
     * @param object $obj reference to the object
     * @param bool $force whether to force the query execution despite security settings
     * @param bool $checkObject check if the object is dirty and clean the attributes
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
     */

    
function insert(&$obj$force false$checkObject true)
    {
        if (
$checkObject != false) {
            if (!
is_object($obj)) {
                
var_dump($obj);
                return 
false;
            }
            
/**
        * @TODO: Change to if (!(class_exists($this->className) && $obj instanceof $this->className)) when going fully PHP5
        */
            
if (!is_a($obj$this->className)) {
                
$obj->setErrors(get_class($obj)." Differs from ".$this->className);
                return 
false;
            }
            if (!
$obj->isDirty()) {
                
$obj->setErrors("Not dirty"); //will usually not be outputted as errors are not displayed when the method returns true, but it can be helpful when troubleshooting code - Mith
                
return true;
            }
        }
        if (!
$obj->cleanVars()) {
            return 
false;
        }

        foreach (
$obj->cleanVars as $k => $v) {
            if (
$obj->vars[$k]['data_type'] == XOBJ_DTYPE_INT) {
                
$cleanvars[$k] = intval($v);
            } elseif ( 
is_array$v ) ) {
                
$cleanvars$k ] = $this->db->quoteStringimplode','$v ) );
            } else {
                
$cleanvars[$k] = $this->db->quoteString($v);
            }
        }
        if (
$obj->isNew()) {
            if (!
is_array($this->keyName)) {
                if (
$cleanvars[$this->keyName] < 1) {
                    
$cleanvars[$this->keyName] = $this->db->genId($this->table.'_'.$this->keyName.'_seq');
                }
            }
            
$sql "INSERT INTO ".$this->table." (".implode(','array_keys($cleanvars)).") VALUES (".implode(','array_values($cleanvars)) .")";
        } else {
            
$sql "UPDATE ".$this->table." SET";
            foreach (
$cleanvars as $key => $value) {
                if ((!
is_array($this->keyName) && $key == $this->keyName) || (is_array($this->keyName) && in_array($key$this->keyName))) {
                    continue;
                }
                if (isset(
$notfirst) ) {
                    
$sql .= ",";
                }
                
$sql .= " ".$key." = ".$value;
                
$notfirst true;
            }
            if (
is_array($this->keyName)) {
                
$whereclause "";
                for (
$i 0$i count($this->keyName); $i++) {
                    if (
$i 0) {
                        
$whereclause .= " AND ";
                    }
                    
$whereclause .= $this->keyName[$i]." = ".$obj->getVar($this->keyName[$i]);
                }
            }
            else {
                
$whereclause $this->keyName." = ".$obj->getVar($this->keyName);
            }
            
$sql .= " WHERE ".$whereclause;
        }
        if (
false != $force) {
            
$result $this->db->queryF($sql);
        } else {
            
$result $this->db->query($sql);
        }
        if (!
$result) {
            return 
false;
        }
        if (
$obj->isNew() && !is_array($this->keyName)) {
            
$obj->assignVar($this->keyName$this->db->getInsertId());
        }
        return 
true;
    }

    
/**
     * Change a value for objects with a certain criteria
     * 
     * @param   string  $fieldname  Name of the field
     * @param   string  $fieldvalue Value to write
     * @param   object  $criteria   {@link CriteriaElement} 
     * 
     * @return  bool
     **/
    
function updateAll($fieldname$fieldvalue$criteria null$force false)
    {
        
$set_clause $fieldname ' = ';
        if ( 
is_numeric$fieldvalue ) ) {
            
$set_clause .=  $fieldvalue;
        } elseif ( 
is_array$fieldvalue ) ) {
            
$set_clause .= $this->db->quoteStringimplode','$fieldvalue ) );
        } else {
            
$set_clause .= $this->db->quoteString$fieldvalue );
        }
        
$sql 'UPDATE '.$this->table.' SET '.$set_clause;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            
$sql .= ' '.$criteria->renderWhere();
        }
        if (
false != $force) {
            
$result $this->db->queryF($sql);
        } else {
            
$result $this->db->query($sql);
        }
        if (!
$result) {
            return 
false;
        }
        return 
true;
    }
    
    function 
updateFieldValue($fieldname$fieldvalue$criteria null$force true)
    {
        
$sql 'UPDATE '.$this->table.' SET '.$fieldname.' = '.$fieldvalue;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            
$sql .= ' '.$criteria->renderWhere();
        }
        if (
false != $force) {
            
$result $this->db->queryF($sql);
        } else {
            
$result $this->db->query($sql);
        }
        if (!
$result) {
            return 
false;
        }
        return 
true;
    }

    
/**
     * delete all objects meeting the conditions
     * 
     * @param object $criteria {@link CriteriaElement} with conditions to meet
     * @return bool
     */

    
function deleteAll($criteria null)
    {
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            
$sql 'DELETE FROM '.$this->table;
            
$sql .= ' '.$criteria->renderWhere();
            if (!
$this->db->query($sql)) {
                return 
false;
            }
            
$rows $this->db->getAffectedRows();
            return 
$rows $rows true;
        }
        return 
false;
    }
    
    function 
objectToArray($objects,$format 's') {
        
$ret = array();
        if(
is_array($objects)) {
            
$i 0;
            foreach(
$objects as $object) {
                
$vars $object->getVars();
                foreach (
$vars as $k => $v) {
                    
$ret[$i][$k] = $object->getVar($k,$format);
                }
                
// Replace external key by corresponding object
                
$externalKey $object->getExternalKey();
                foreach(
$externalKey as $k => $v) {
                    if(
$v['core']) {
                        
$handler xoops_gethandler($v['className']);
                    } else {
                        
$handler xoops_getmodulehandler($v['className'], 'extgallery');
                    }
                    
$ret[$i][$v['keyName']] = $this->objectToArrayWithoutExternalKey($handler->$v['getMethodeName']($ret[$i][$k]),$format);
                    unset(
$ret[$i][$k]);
                }
                
$i++;
            }
        } else {
            
$vars $objects->getVars();
            foreach (
$vars as $k => $v) {
                
$ret[$k] = $objects->getVar($k,$format);
            }
            
// Replace external key by corresponding object
            
$externalKey $objects->getExternalKey();
            foreach(
$externalKey as $k => $v) {
                if(
$v['core']) {
                    
$handler xoops_gethandler($v['className']);
                } else {
                    
$handler xoops_getmodulehandler($v['className'], 'extgallery');
                }
                
$ret[$v['keyName']] = $this->objectToArrayWithoutExternalKey($handler->$v['getMethodeName']($ret[$k]),$format);
                unset(
$ret[$k]);
            }
        }
        return 
$ret;
    }
    
    function 
objectToArrayWithoutExternalKey($object,$format 's') {
        
$ret = array();
        if(
$object != null) {
            
$vars $object->getVars();
            foreach (
$vars as $k => $v) {
                
$ret[$k] = $object->getVar($k,$format);
            }
        }
        return 
$ret;
    }
    
    function 
updateCounter($fieldname,$criteria,$op='+') {    
        
$sql 'UPDATE '.$this->table.' SET '.$fieldname.' = '.$fieldname.$op.'1';
        
$sql .= ' '.$criteria->renderWhere();
        
$result $this->db->queryF($sql);
        if (!
$result) {
            return 
false;
        }
        return 
true;
    }
    
    function 
getSum($criteria null,$sum '*')
    {
        
$field "";
        
$groupby false;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            if (
$criteria->groupby != "") {
                
$groupby true;
                
$field $criteria->groupby.", "//Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
            
}
        }
        
$sql 'SELECT '.$field."SUM($sum) FROM ".$this->table;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            
$sql .= ' '.$criteria->renderWhere();
            if (
$criteria->groupby != "") {
                
$sql .= $criteria->getGroupby();
            }
        }
        
$result $this->db->query($sql);
        if (!
$result) {
            return 
0;
        }
        if (
$groupby == false) {
            list(
$sum) = $this->db->fetchRow($result);
            return 
$sum;
        }
        else {
            
$ret = array();
            while (list(
$id$sum) = $this->db->fetchRow($result)) {
                
$ret[$id] = $sum;
            }
            return 
$ret;
        }
    }
    
    function 
getMax($criteria null,$max '*')
    {
        
$field "";
        
$groupby false;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            if (
$criteria->groupby != "") {
                
$groupby true;
                
$field $criteria->groupby.", "//Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
            
}
        }
        
$sql 'SELECT '.$field."MAX($sum) FROM ".$this->table;
        if (isset(
$criteria) && is_subclass_of($criteria'criteriaelement')) {
            
$sql .= ' '.$criteria->renderWhere();
            if (
$criteria->groupby != "") {
                
$sql .= $criteria->getGroupby();
            }
        }
        
$result $this->db->query($sql);
        if (!
$result) {
            return 
0;
        }
        if (
$groupby == false) {
            list(
$max) = $this->db->fetchRow($result);
            return 
$max;
        } else {
            
$ret = array();
            while (list(
$id$max) = $this->db->fetchRow($result)) {
                
$ret[$id] = $max;
            }
            return 
$ret;
        }
    }
    
}


3- Il faut créer la classe correspondant aux infos de la BDD. Dans ce cas là il sagit de la classe : ExtgalleryCat
C'est dans celle-ci que le model objet de XOOPS est utilisé. La partie externalKey est une partie que j'ai rajoutée. Ca en ait encors au stade expérimental.
class ExtgalleryCat extends XoopsObject
{

    var 
$externalKey = array();

    function 
ExtgalleryCat()
    {
        
$this->initVar('cat_id'XOBJ_DTYPE_INT0false);
        
$this->initVar('cat_pid'XOBJ_DTYPE_INT0false);
        
$this->initVar('cat_limit_inf'XOBJ_DTYPE_INT0false);
        
$this->initVar('cat_limit_sup'XOBJ_DTYPE_INT0false);
        
$this->initVar('cat_level'XOBJ_DTYPE_INT0false);
        
$this->initVar('cat_name'XOBJ_DTYPE_TXTBOX''false255);
        
$this->initVar('cat_desc'XOBJ_DTYPE_TXTAREA''true);
        
$this->initVar('cat_nb_album'XOBJ_DTYPE_INT0false);
        
$this->initVar('cat_nb_photo'XOBJ_DTYPE_INT0false);
        
$this->initVar('cat_date'XOBJ_DTYPE_INT0false);
        
$this->initVar('photo_id'XOBJ_DTYPE_INT0false);
        
$this->initVar('uid'XOBJ_DTYPE_INT0false);
        
        
$this->externalKey['photo_id'] = array('className'=>'photo''getMethodeName'=>'getPhoto''keyName'=>'photo''core'=>false);
        
$this->externalKey['uid'] = array('className'=>'user''getMethodeName'=>'get''keyName'=>'user''core'=>true);
    }
    
    public function 
getExternalKey() {
        return 
$this->externalKey;
    }
    
}


4- Enfin, il faut créer la classe de manipulation (Handler) de la classe métier (ExtgalleryCat dans ce cas). C'est de cette classe que l'on se servirra dans le module pour effectuer toutes les opérations. Les méthodes la composant son à adapté en fonction de l'utilisation des objets.
class ExtgalleryCatHandler extends ExtgalleryPersistableObjectHandler {
    
    var 
$xoopsObjectTree;
    var 
$cache = array();
        
    function 
ExtgalleryCatHandler(&$db)
    {
        
$this->ExtgalleryPersistableObjectHandler($db'extgallery_cat''ExtgalleryCat''cat_id');
    }
    
    public function 
createCat($data)
    {
        
$cat $this->create();
        
$cat->setVars($data);
        
        
$limitSup null;
        
$level null;
        
        
// If have parent cat, check it's a node and not a leaf
        
$pid $cat->getVar('cat_pid');
        if(
$pid != 0) {
            
$parentCat $this->getCat(pid);
            if((
$parentCat->getVar('cat_limit_sup') - $parentCat->getVar('cat_limit_inf')) == && $parentCat->getVar('cat_nb_photo') != 0) {
                return 
false;
            }
            
$limitSup $parentCat->getVar('cat_limit_sup');
            
$level $parentCat->getVar('cat_level') + 1;
        } else {
            
$limitSup $this->getMax(null,'cat_limit_sup');
            
$level 0;
        }
        
        
// Update cat_nb_album
        
if(($parentCat->getVar('cat_limit_sup') - $parentCat->getVar('cat_limit_inf')) == 1) {
            
$criteria = new Criteria('cat_id',$parentCat->getVar('cat_id'));
            
$this->updateCounter('cat_nb_album',$criteria);
        } else {
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$parentCat->getVar('cat_limit_inf'),'<='));
            
$criteria->add(new Criteria('cat_limit_sup',$parentCat->getVar('cat_limit_sup'),'>='));
            
$this->updateCounter('cat_nb_album',$criteria);
        }
        
        
// Update cat_limit_sup if have parent cat
        
if($pid != 0) {
            
$criteria = new Criteria('cat_limit_sup',$limitSup,'>=');
            if(
$this->updateFieldValue('cat_limit_sup''cat_limit_sup + 2'$criteria)) {
                return 
false;
            }
        }
        
        
$cat->setVar('cat_limit_inf',$limitSup);
        
$cat->setVar('cat_limit_sup',$limitSup+1);
        
$cat->setVar('cat_level',$level);
        
        return 
$this->insert($cat);
    }
    
    public function 
modifyCat($data) {
        
$cat $this->get($data['cat_id']);
        
// If parent cat change
        
if($data['cat_pid'] != $cat->getVar('cat_pid')) {
            
            
$oldParent $this->get($cat->getVar('cat_pid'));
            
$newParent $this->get($data['cat_pid']);
        
            
// Check that new parent cat is a node
            
if(($newParent->getVar('cat_limit_sup') - $newParent->getVar('cat_limit_inf')) == && $newParent->getVar('cat_nb_photo') != 0) {
                return 
false;
            }
            
            
// Check that new parent cat isn't under this cat in tree
            
if($newParent->getVar('cat_limit_inf') > $cat->getVar('cat_limit_inf') && $newParent->getVar('cat_limit_sup') < $cat->getVar('cat_limit_sup')) {
                return 
false;
            }
            
            
// Update cat_nb_album of old parent
            
$nbAlbum $cat->getVar('cat_nb_album') == $cat->getVar('cat_nb_album');
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf'),'<'));
            
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'>'));
            if(
$oldParent->getVar('cat_nb_album') == 1) {
                
$criteria->add(new Criteria('cat_level',$oldParent->getVar('cat_level')));
            }
            
$this->updateFieldValue('cat_nb_album'"cat_nb_album - $nbAlbum"$criteria);
            
            
// Update cat_nb_photo of old parent
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf'),'<'));
            
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'>'));
            
$this->updateFieldValue('cat_nb_photo'"cat_nb_photo - ".$cat->getVar('cat_nb_photo'), $criteria);
            
            
// ### Move sub tree in the new cat ###
            
            // Enlarge new parent cat width
            
$catWidth $cat->getVar('cat_limit_sup') - $cat->getVar('cat_limit_inf') + 1;
            
            
$criteria = new Criteria('cat_limit_sup',$newParent->getVar('cat_limit_sup'),'>');
            
$this->updateFieldValue('cat_limit_inf'"cat_limit_inf + $catWidth"$criteria);
            
            
$criteria = new Criteria('cat_limit_sup',$newParent->getVar('cat_limit_sup'),'>=');
            
$this->updateFieldValue('cat_limit_sup'"cat_limit_sup + $catWidth"$criteria);
            
            
$moveWidth $newParent->getVar('cat_limit_sup') - $cat->getVar('cat_limit_inf') - $catWidth;
            
            
// Move cat_limit_sup of sub tree to new value
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf') + $catWidth,'>='));
            
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup') + $catWidth,'<='));
            
$this->updateFieldValue('cat_limit_inf'"cat_limit_inf + $moveWidth"$criteria);
            
            
// Move cat_limit_inf of sub tree to new value
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf') + $catWidth $moveWidth,'>='));
            
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup') + $catWidth,'<='));
            
$this->updateFieldValue('cat_limit_sup'"cat_limit_sup + $moveWidth"$criteria);
            
            
// Remove the break in limit at the old place of cat
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_sup'),'>'));
            
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'>'));
            
$this->updateFieldValue('cat_limit_inf'"cat_limit_inf - $catWidth"$criteria);
            
$criteria = new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'>');
            
$this->updateFieldValue('cat_limit_sup'"cat_limit_sup - $catWidth"$criteria);
            
            
// ###  END Move sub tree in the new cat END ###
            
            // Get the cat with limit updated
            
$cat $this->get($data['cat_id']);
            
            
// Update cat level for the move's tree
            
if($newParent->getVar('cat_level') != $cat->getVar('cat_level') - 1) {
                
$diffLevel $newParent->getVar('cat_level') - $cat->getVar('cat_level') + 1;
                
$criteria = new CriteriaCompo();
                
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf'),'>='));
                
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'<='));
                
$this->updateFieldValue('cat_level'"cat_level + $diffLevel"$criteria);
            }
            
            
// Update cat_nb_album of new parent
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf'),'<'));
            
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'>'));
            if(
$newParent->getVar('cat_nb_album') == 0) {
                
$criteria->add(new Criteria('cat_level',$newParent->getVar('cat_level')));
            }
            
$this->updateFieldValue('cat_nb_album'"cat_nb_album + $nbAlbum"$criteria);
            
            
// Update cat_nb_photo of new parent
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf'),'<'));
            
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'>'));
            
$this->updateFieldValue('cat_nb_photo'"cat_nb_photo + ".$cat->getVar('cat_nb_photo'), $criteria);
            
            
// Get the cat with updated data
            
$cat $this->get($data['cat_id']);
            echo 
'test';
        }
        
        
$cat->assignVars($data);
        
$this->insert($cat);
    }
    
    public function 
deleteCat($catId) {
        
/*if(!isset($this->xoopsObjectTree)) {
            $this->xoopsObjectTree = new XoopsObjectTree($this->getAllCat(),'cat_id','cat_pid');
        }
        $this->deletePhotos($catId);
        $firstChilds = $this->xoopsObjectTree->getFirstChild($catId);
        foreach($firstChilds as $cat) {
            $this->deleteCat($cat->getVar('cat_id'));
        }
        $this->delete($catId);*/
    
}
    
    private function 
deletePhotos($catId) {
        
/*$photoHandler = xoops_getmodulehandler('photo', 'extgallery');
        $criteria = new Criteria('cat_id',$catId);
        $photoHandler->deleteAll($criteria);*/
    
}
    
    public function 
getCat($catId) {
        return 
$this->get($catId);
    }
    
    public function 
getAllCat() {
        
/*return $this->getObjects();*/
    
}
    
    public function 
getFirstChild(&$cat) {
        if(
$cat->getVar('cat_id') == 0) {
            
$criteria = new Criteria('cat_level'1);
            
$criteria->setOrder('cat_limit_inf');
        } else {
            
$criteria = new CriteriaCompo();
            
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf'),'>'));
            
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'<'));
            
$criteria->add(new Criteria('cat_level',$cat->getVar('cat_level') + 1));
            
$criteria->setOrder('cat_limit_inf');
        }
        return 
$this->getObjects($criteria);
    }
    
    public function 
getParentTree(&$cat) {
        
$criteria = new CriteriaCompo();
        
$criteria->add(new Criteria('cat_limit_inf',$cat->getVar('cat_limit_inf'),'<'));
        
$criteria->add(new Criteria('cat_limit_sup',$cat->getVar('cat_limit_sup'),'>'));
        
$criteria->setOrder('cat_limit_inf');
        return 
$this->getObjects($criteria);
    }
    
    public function 
getNbAlbum() {
        
/*$criteria = new Criteria('cat_nb_album',0);
        return $this->getCount($criteria);*/
    
}
    
    
// Return only category
    
public function getPublicCatSelect($optionName$selected='') {
        
/*$criteria = new CriteriaCompo();
        $criteria->add(new Criteria('uid',0));
        // isCategory test
        $criteria->add(new Criteria('cat_nb_photo',0));
        $criteria->add(new Criteria('cat_nb_album',0,'!='),'OR');
        $xoopsObjectTree = new XoopsObjectTree($this->getObjects($criteria),'cat_id','cat_pid');
        return $xoopsObjectTree->makeSelBox($optionName, 'cat_name', '-', $selected, true);*/
    
}
    
    
// Return category and album
    
public function getAllPublicCatSelect($optionName$selected=''$addEmptyOption false) {
        
/*$criteria = new Criteria('uid',0);
        $xoopsObjectTree = new XoopsObjectTree($this->getObjects($criteria),'cat_id','cat_pid');
        return $xoopsObjectTree->makeSelBox($optionName, 'cat_name', '-', $selected, $addEmptyOption);*/
    
}
    
    public function 
getUsersHaveCat() {
        
/*$criteria = new Criteria('uid',0,"!=");
        $cats = $this->getObjects($criteria);
        $users = array();
        $userHandler = xoops_gethandler('user');
        foreach($cats as $cat) {
            if(!isset($users[$cat->getVar('uid')])) {
                $user = $userHandler->get($cat->getVar('uid'));
                $users[$user->getVar('uid')] = $user;
            }
        }
        return $users;*/
    
}
    
    
// Return only category
    
public function getPrivateCatSelect($optionName$selected='') {
        
/*$criteria = new CriteriaCompo();
        $criteria->add(new Criteria('uid',0,"!="));
        // isCategory test
        $criteria->add(new Criteria('cat_nb_photo',0));
        $criteria->add(new Criteria('cat_nb_album',0,'!='),'OR');
        $xoopsObjectTree = new XoopsObjectTree($this->getObjects($criteria),'cat_id','cat_pid');
        return $xoopsObjectTree->makeSelBox($optionName, 'cat_name', '-', $selected, true);*/
    
}
    
    
// Return category and album
    
function getAllPrivateCatSelect($optionName$selected=''$addEmptyOption false) {
        
/*$criteria = new Criteria('uid',0,"!=");
        $xoopsObjectTree = new XoopsObjectTree($this->getObjects($criteria),'cat_id','cat_pid');
        return $xoopsObjectTree->makeSelBox($optionName, 'cat_name', '-', $selected, $addEmptyOption);*/
    
}
    
    function 
getPublicNodeSelect($optionName$selected='') {
        
$criteria = new CriteriaCompo();
        
$criteria->add(new Criteria('uid',0));
        
$criteria->add(new Criteria('cat_limit_sup - cat_limit_inf',1,">"));
        
$criteria->setSort('cat_limit_inf');
        return 
$this->makeSelBox($this->getObjects($criteria),$optionName'cat_name''cat_id'$selectedtrue);
    }
    
    function 
makeSelBox($objects$optionName$fieldName$filedValue$selected=''$addEmptyOption false) {
        
$ret '<select name='.$optionName.'>';
        if (
false != $addEmptyOption) {
            
$ret .= '<option value="0">&nbsp;</option>';
        }
        foreach(
$objects as $object) {
            
$ret .= '<option value="'.$object->getVar($filedValue).'">'.$object->getVar($fieldName).'</option>';
        }
        return 
$ret.'</select>';
    }
    
}


Ca fait un poste assez long, désolé. Si tu a des questions n'hésite pas.

A+

Posté le : 10/06/2006 01:04
Partager Twitter Partagez cette article sur GG+
Re: Methode pour inserer des données dans la base
Aspirant
Inscrit: 05/07/2003 12:24
Messages: 73
Salut,

Merci pour ta (votre je sais pas si tu preferes le tu ou le vous) réponse (super précise ), je me penche la dessus, et si je bloque je te pose des questions.

Hum, j'ai l'impression que tu retravail sur ton module ExtGal (si c'est ca, c'est une bonne nouvelle, car par mal de monde etait content des deux premières versions).

Pour etre sûr, la classe PersistableObjectHandler fonctionne sur une xoops 2.0.13 ?

Merci encore, à bientot.

Posté le : 10/06/2006 08:50
Partager Twitter Partagez cette article sur GG+
Re: Methode pour inserer des données dans la base
Semi pro
Inscrit: 06/01/2004 09:37
De Non loin de Paris
Messages: 666
Oui elle fonctionne mais elle n'est pas incluse dans les version de XOOPS 2.0. Il te faut donc l'inclure dans ton repertoire class en la renomant en la préfixant par le nom de ton module.

A+

PS : le "tu" fait parfaitement l'affaire

Posté le : 10/06/2006 08:53
Partager Twitter Partagez cette article sur GG+
Re: Methode pour inserer des données dans la base
Newbie
Inscrit: 03/08/2007 13:50
Messages: 18
Bonjour Zoulou,

j'essaye d'adapter le module extgallery pour faire un module de concours...

Pour cela, il me faut 2 variables et donc 2 champs dans la db de plus.

Je suis un peu perdu, car je ne trouves pas de sql sur ce module (du moins qu'il soit visible...)

J'ai ainsi créer mes 2 variables et mes 2 champs de bd au même nom, et tente de les envoyer par :

$data = array(
                            
'cat_pid'=>$_POST['cat_pid'],
                            
'cat_name'=>$_POST['cat_name'],
                            
'cat_desc'=>$_POST['cat_desc'],
                            
'cat_weight'=>$_POST['cat_weight'],
                            
'cat_date'=>time(),
                            
'cat_date_comm'=>$_POST['cat_date_comm'],
                            
'cat_date_posts'=>$_POST['cat_date_posts'],
                            
'cat_imgurl'=>$_POST['cat_imgurl']
                            
                        );
                
$catHandler->createCat($data);

                
redirect_header("public-category.php"3_AM_EXTGALLERY_CAT_CREATED);


Les 2 avant derniers posts sont mes 2 champs.

Mais rien n'apparait dans la bd...

Si vous pouviez m'aider...

Merci d'avance.

Posté le : 30/11/2007 08:20
Partager Twitter Partagez cette article sur GG+

 Haut   Précédent   Suivant



Vous pouvez voir les sujets.
Vous ne pouvez pas débuter de nouveaux sujets.
Vous ne pouvez pas répondre aux contributions.
Vous ne pouvez pas éditer vos contributions.
Vous ne pouvez pas effacez vos contributions.
Vous ne pouvez pas ajouter de nouveaux sondages.
Vous ne pouvez pas voter en sondage.
Vous ne pouvez pas attacher des fichiers à vos contributions.
Vous ne pouvez pas poster sans approbation.

Propulsé avec XOOPS | Graphisme adapté par Tatane, Grosdunord, Montuy337513

87 Personne(s) en ligne (69 Personne(s) connectée(s) sur Forum) | Utilisateur(s): 0 | Invité(s): 87 | Plus ...