Créer un compte ou loggez-vous pour pouvoir ajouter, commenter et noter les snippets.

Navigation

Tags relatifs

my Symfony Plugins

Plugins demos


My bookmarks

Vous pouvez commenter/noter en utilisant le compte anonymous (mot de passe: anonymous)
You can comment/rate using the anonymous account (password: anonymous).

Snippets taggés : "mysql" Snippets taggés : "mysql"

[MySQL] Sauvegarde basique de base - 444 view(s)

mysqldump -u root -p maBase > maBase_backup.sql
par COil le 2009-05-08, taggé : backup  mysql  ubuntu 
(1 commentaire)

[MySQL] Restoration basique d'une base en ligne de commande - 164 view(s)

On aura au préalable coché les commandes de destruction de l'ancienne base lors de l'exportation de la base.

mysql -h #serveur# -u #username# -p #database# < #dump_file#
par COil le 2008-11-25, taggé : bash  database  dump  mysql  restore 
(1 commentaire)

[MySQL] Lancer le server sans la vérifications des droits - 133 view(s)

Mots de passe dans: my.cnf

On arrête mysql :

# /etc/init.d/mysql stop
 

On le relance sans les droits d'utilisateur :

# mysqld --skip-grant-tables &
 

On lance le client mysql en ligne de commande :

# mysql -u root
 

On fait les modifs nécessaires et on quitte le client. On arrête mysql :

# killall mysqld
 

On le relance normalement :

# /etc/init.d/mysql start
 
par COil le 2008-09-29, taggé : mysql  password  restart  rights 
(1 commentaire)

[MySQL] Nommer index et clés étrangères pour les scripts de migration symfony - 157 view(s)

Permet de pouvoir faire des scripts de migration fiables puisque les noms de clé et d'index seront les mêmes sur tout les serveurs.

<?php
 
/**
 * Migration qui ajoute les colonne permettant d'effectuer la localisation
 * d'un membre comme les bars.
 */
 
class Migration024 extends sfMigration 
{
 
  /**
   * Up
   */
  public function up() 
  {
    $this->diag('Debut UP 24');
 
    // Table user_profile
    $this->diag('MAJ champs user_profile');
    $this->executeSQL("
ALTER TABLE `user_profile` 
ADD `country_code` varchar(2) default NULL COMMENT 'Code du pays' AFTER `personal_url` ,
ADD `zone_id` int(11) default NULL COMMENT 'Departement du membre' AFTER `country_code` ,
ADD `lat` decimal(12,9) default NULL COMMENT 'Latitude' AFTER `zone_id` ,
ADD `lng` decimal(12,9) default NULL COMMENT 'Longitude' AFTER `lat` ,
ADD `latlng_precision` int( 11 ) default NULL COMMENT 'Precision de la localisation' AFTER `lng`;
    ");
 
    // ALTER TABLE `user_profile` ADD FOREIGN KEY ( `zone_id` ) REFERENCES `zone` (`id`) ON DELETE SET NULL;
    // Ajout des cle etrangeres
    $this->diag('MAJ contraintes user_profile');
    $this->executeSQL("    
ALTER TABLE `user_profile`
 ADD CONSTRAINT `zone_id_FK`
 FOREIGN KEY `zone_id_idx` ( `zone_id` )
 REFERENCES `zone` (`id`)
 ON DELETE SET NULL;
");
 
  }
 
  /**
   * Down
   */
  public function down() 
  {
    $this->diag('Debut DOWN 24');
 
    // Suppr
    $this->diag('SUPPRESSION contraintes champs a supprimer');
 
    $this->executeSQL("
      ALTER TABLE `user_profile`
      DROP FOREIGN KEY `zone_id_FK`
    ");
 
    $this->executeSQL("
      DROP INDEX `zone_id_idx` ON `user_profile` 
    ");
 
    $this->diag('SUPPRESSION champs user_profile');
    $this->executeSQL("
ALTER TABLE `user_profile`
  DROP `country_code`,
  DROP `zone_id`,
  DROP `lat`,
  DROP `lng`,
  DROP `town`,
  DROP `latlng_precision`;    
    ");
  }
}
 

Ou en décomposant la création des index/clés

<?php
 
/**
 * Migration qui ajoute les colonne permettant d'effectuer la localisation
 * d'un membre comme les bars.
 */
 
class Migration024 extends sfMigration 
{
 
  /**
   * Up
   */
  public function up() 
  {
    $this->diag('Debut UP 24');
 
    // Table am_user_profile
    $this->diag('MAJ champs user_profile');
    $this->executeSQL("
ALTER TABLE `user_profile` 
ADD `country_code` varchar(2) default NULL COMMENT 'Code du pays' AFTER `personal_url` ,
ADD `lat` decimal(12,9) default NULL COMMENT 'Latitude' AFTER `country_code` ,
ADD `lng` decimal(12,9) default NULL COMMENT 'Longitude' AFTER `lat` ,
ADD `latlng_precision` int( 11 ) default NULL COMMENT 'Precision de la localisation' AFTER `lng`;
    ");
 
    // ALTER TABLE `am_user_profile` ADD FOREIGN KEY ( `zone_id` ) REFERENCES `am_zone` (`id`) ON DELETE SET NULL;
    // Ajout des cle etrangeres
    /*
    $this->diag('MAJ conrtaintes am_user_profile');
    $this->executeSQL("    
ALTER TABLE `user_profile`
 ADD CONSTRAINT `zone_id_FK`
 FOREIGN KEY `zone_id_idx` ( `zone_id` )
 REFERENCES `am_zone` (`id`)
 ON DELETE SET NULL;
");
  */
    $this->diag('CREATION table am_user_zone');
    $this->executeSQL("        
CREATE TABLE `user_zone` (
  `id` int(11) NOT NULL auto_increment,
  `user_id` int(11) NOT NULL,
  `zone_id` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;    
");
 
/*
  KEY `user_zone_FI_1` (`user_id`),
  KEY `user_zone_FI_2` (`zone_id`)
  ALTER TABLE `user_zone` ADD INDEX ( `user_id` )  
*/
 
    $this->diag('MAJ conrtaintes am_user_zone');
    $this->executeSQL("
ALTER TABLE `user_zone` 
ADD INDEX `user_zone_FI_1` ( `user_id` )         
    ");
    $this->executeSQL("     
ALTER TABLE `user_zone` 
ADD FOREIGN KEY `user_zone_FK_1` ( `user_id` ) 
REFERENCES `sf_guard_user` (`id` ) ON DELETE CASCADE;
");
 
    $this->executeSQL("
ALTER TABLE `user_zone` ADD INDEX `am_user_zone_FI_2` ( `zone_id` )         
    ");
    $this->executeSQL("     
ALTER TABLE `user_zone` 
ADD FOREIGN KEY `user_zone_FK_2` ( `zone_id` ) 
REFERENCES `zone` (`id` ) ON DELETE CASCADE;
");
 
  }
 
  /**
   * Down
   */
  public function down() 
  {
    $this->diag('Debut DOWN 24');
 
    // Suppr
    $this->diag('SUPPRESSION contraintes champs a supprimer');
 
    /*
    $this->executeSQL("
      ALTER TABLE `user_profile`
      DROP FOREIGN KEY `zone_id_FK`
    ");
 
    $this->executeSQL("
      DROP INDEX `zone_id_idx` ON `user_profile` 
    ");
    */
 
    $this->diag('SUPPRESSION champs user_profile');
    $this->executeSQL("
ALTER TABLE `user_profile`
  DROP `country_code`,
  DROP `lat`,
  DROP `lng`,
  DROP `latlng_precision`;    
    ");
 
    $this->diag('SUPPRESSION table user_zone');
    $this->executeSQL("DROP TABLE IF EXISTS `user_zone`");
  }
}
 
par COil le 2008-09-29, taggé : constraint  index  migration  mysql  plugin  propel  symfony 
(1 commentaire)

[Propel] Accéder à plusieurs bases de donnée dans une application - 120 view(s)

all:
  connexion1:
    class:          sfPropelDatabase
    param:
      dsn:          mysql://root:password@localhost/db1
  connexion2:
    class:          sfPropelDatabase
    param:
      dsn:          mysql://root:password@localhost/db2
 

Après tu peux instancier une connection depuis propel :

$con1 = Propel::getConnection('connexion1');
$con2 = Propel::getConnection('connexion2');
 
par COil le 2008-09-29, taggé : database  mysql  propel 
(1 commentaire)

[Propel] Criterion simple - 112 view(s)

    $criterion = $c->getNewCriterion(self::RESPONSE_CODE, null, Criteria::ISNOTNULL)
      ->addAnd($c->getNewCriterion(self::RESPONSE_CODE, 0));
    $c->add($criterion);
 
par COil le 2008-09-29, taggé : criteria  criterion  mysql 
(1 commentaire)

[Propel] Dans un criteria custom faire fi des secondes et minutes pour la comparaison de dates - 133 view(s)

2ere maniere full mysql (donc plus safe)

$criterion->addAnd($c->getNewCriterion(ShopOrderPeer::CREATED_AT, 'DATE('. ShopOrderPeer::CREATED_AT. ')  <= \''. goDate::getMySqlDateFromTs($this->filters['created_at']['to']). '\'', Criteria::CUSTOM)); 
$criterion->addAnd($c->getNewCriterion(ShopOrderPeer::CREATED_AT, 'DATE('. ShopOrderPeer::CREATED_AT. ')  <= DATE(FROM_UNIXTIME('. $this->filters['created_at']['to']. '))', Criteria::CUSTOM));
 
par COil le 2008-09-29, taggé : criteria  criterion  custom  date  mysql  propel  timestamp 
(1 commentaire)

[Propel] Utiliser des fonctions mysql multiples dans un addSelectColumn - 205 view(s)

Appliquer le patch suivant a propel:

--> http://propel.phpdb.org/trac/ticket/425

par COil le 2008-09-29, taggé : addselectcolumn  bug  criteria  mysql  propel 
(1 commentaire)

[Propel] Exemple d'utilisation de criterions - 123 view(s)

Exemple 1:

      $criterion = null;
      $form_product_state_id = array_flip($form_product_state_id);
 
      // Test avec neuf
      $with_new = isset($form_product_state_id[0]);
      if ($with_new) {
        unset($form_product_state_id[0]);
      }
 
      // Seulement neuf ou au moins un des autres etatss ?
      if ($form_product_state_id) {
        $criterion = $c->getNewCriterion(ShopProductPeer::PRODUCT_STATE_ID, array_keys($form_product_state_id), Criteria::IN);
      }
 
      // Produits neufs
      if ($with_new) {
        if (!$criterion) {
          $criterion = $c->getNewCriterion(ShopProductPeer::PRODUCT_STATE_ID, null, Criteria::ISNULL);
        } else {
          $criterion->addOr($c->getNewCriterion(ShopProductPeer::PRODUCT_STATE_ID, null, Criteria::ISNULL));
        }  
      }
      $c->add($criterion);
 

Exemple 2

  /**
   * Recuperation d'un produit par son code EAN
   *
   * @author lvernet
   * @since 18 sept. 07
   */
  public static function doSelectByEan($ean, Criteria $c = null)
  {
    if ($c == null) {
      $c = new Criteria();
    }
 
    $ean = trim($ean);
    $padded_ean = str_pad($ean, ProductEan::EAN_STD_LENGTH, ProductEan::EAN_PADDING_CHAR, STR_PAD_LEFT);
 
    ProductPeer::isVisibleCriteria($c);
    $c->addJoin(ProductPeer::ID, self::PRODUCT_ID);
 
    // Test par recherche stricte
    $criterion = $c->getNewCriterion(self::EAN13, $ean);
 
    // Test en completant a gauche a saisie utilisateur par des 0 a 13 caraceteres
    $criterion->addOr($c->getNewCriterion(self::EAN13, $padded_ean));
 
    // Test en completant a gauche le code barre en base par des 0 a 13 caraceteres
    $criterion->addOr($c->getNewCriterion(self::EAN13, 'LPAD('. self::EAN13 .' , 13,  \'0\') = \''. $ean. '\'', Criteria::CUSTOM));
 
    // Test en completant a gauche des codes barres et la saisie utilisateur
    $criterion->addOr($c->getNewCriterion(self::EAN13, 'LPAD('. self::EAN13 .' , 13,  \'0\') = \''. $padded_ean. '\'', Criteria::CUSTOM));
 
    // Exec
    $c->add($criterion);
    $product_ean = self::doSelectOne($c);
 
    return $product_ean ? $product_ean : null;
  }
 
par COil le 2008-09-29, taggé : criteria  criterion  mysql  propel 
(1 commentaire)

[Propel] Criterion et left join sur 3 tables - 144 view(s)

$c = $shop->buildPkeyCriteria();
 
 $c->addJoin(ClientQuestionPeer::SHOP_PRODUCT_ID, ShopProductPeer::ID, Criteria::LEFT_JOIN);
    $c->addJoin(ClientQuestionPeer::SHOP_ORDER_ID, ShopOrderPeer::ID, Criteria::LEFT_JOIN);
 
    $criterion = $c->getNewCriterion(ShopOrderPeer::SHOP_ID, $shop->getId())
      ->addOr($c->getNewCriterion(ShopProductPeer::SHOP_ID, $shop->getId()));
    $c->addAnd($criterion);
 
    $c->addDescendingOrderByColumn(self::CREATED_AT);
    return $c;
 
par COil le 2008-09-29, taggé : join  mysql  propel 
(1 commentaire)

[Propel] Faire un update de masse par criteria - 174 view(s)

    $con = Propel::getConnection();
 
    $selectCriteria = new Criteria();
    $selectCriteria->add(StaticTemplatesPeer::CODE, $code);        
    $selectCriteria->add(StaticTemplatesPeer::IS_ACTIVE, true);
    $ids = goPropelTools::getIdTab(self::doSelect($selectCriteria));
 
    $updateCriteria = new Criteria();
    $updateCriteria->add(self::ID, $ids, Criteria::IN);
    $updateCriteria->add(StaticTemplatesPeer::IS_ACTIVE, false);
 
    return self::doUpdate($updateCriteria);
 
par COil le 2008-09-29, taggé : mysql  peer  propel  update 
(1 commentaire)

[Propel] Faire une fonction custom de join - 143 view(s)

public static function doSelectJoinUserAndStateAndCountry(Criteria $c, $con = null) {
$c = clone $c;
 
if ($c->getDbName() == Propel::getDefaultDB()) {
$c->setDbName(self::DATABASE_NAME);
}
 
MemberPeer::addSelectColumns($c);
$startcol2 = (MemberPeer::NUM_COLUMNS - MemberPeer::NUM_LAZY_LOAD_COLUMNS) + 1;
 
UserPeer::addSelectColumns($c);
$startcol3 = $startcol2 + UserPeer::NUM_COLUMNS ;
 
CountryPeer::addSelectColumns($c);
$startcol4 = $startcol3 + CountryPeer::NUM_COLUMNS ;
 
StatePeer::addSelectColumns($c);
CountryPeer::addSelectColumns($c);
 
 
$c->addJoin(MemberPeer::USER_ID, UserPeer::ID);
$c->addJoin(MemberPeer::STATE_ID, StatePeer::ID);
$c->addJoin(MemberPeer::COUNTRY_ID, CountryPeer::ID);
 
 
$rs = BasePeer::doSelect($c, $con);
$results = array();
 
while($rs->next())
{
$omClass = MemberPeer::getOMClass();
 
$cls = Propel::import($omClass);
$obj1 = new $cls();
$obj1->hydrate($rs);
 
$omClass = UserPeer::getOMClass();
 
$cls = Propel::import($omClass);
$obj2 = new $cls();
$obj2->hydrate($rs, $startcol2);
 
$omClass = StatePeer::getOMClass();
 
$cls = Propel::import($omClass);
$obj3 = new $cls();
$obj3->hydrate($rs, $startcol3);
 
$omClass = CountryPeer::getOMClass();
 
$cls = Propel::import($omClass);
$obj4 = new $cls();
$obj4->hydrate($rs, $startcol4);
 
$obj1->setUser($obj2);
$obj1->setState($obj3);
$obj1->setState($obj4);
$results[] = $obj1;
}
 
return $results;
}
 
par COil le 2008-09-29, taggé : custom  hydrate  import  join  mysql  propel 
(1 commentaire)

[symfony errors] Page blanche même en dev lors de la construction d'une requête par criterion - 231 view(s)

/!\ Les fonctions de criterion n'acceptent que des autres criterions en parametre /!\

/!\ Appel d'une methode doSelect sans passer de criteria /!\

/!\ Passage d'une valeur nulle ou d'un objet quelquonque a place d'un criteria /!\

par COil le 2008-09-29, taggé : criteria  criterion  error  mysql  propel  sferrors  symfony 
(1 commentaire)

[symfony] Encapsulation d'ordres SQL dans un bloc try/catch avec commit et rollback - 256 view(s)

// Debut de la transaction
      $con = Propel::getConnection();
      $con->begin();      
      try
      { 
        $this->shop_ribs->saveShopRibsFromRequest($shop_ribs_form);
        $this->shop->setShopRibs($this->shop_ribs);
        $this->shop->save();
        $con->commit();
      }
      catch (Exception $e)
      {
        $con->rollback();
        $this->getRequest()->setError('error', $this->getContext()->getI18N()->__('Une erreur est survenue pendant l\'enregistrement, veuillez essayer d\'ici quelques minutes.'));
      }
 
par COil le 2008-09-29, taggé : catch  mysql  propel  symfony  try 
(1 commentaire)

[Propel] Chaîne de connection MySQL typique - 107 view(s)

A utiliser dans le database.yml et le propel.ini:

mysql://user:password@host/database-name
 

Or you can use the explicit synthax:

dev:
  propel:
    class:      sfPropelDatabase
    param:
      phptype:  mysql
      host:     localhost
      hostspec: localhost
      database: db
      username: user
      password: ~
      compat_assoc_lower: true
      compat_rtrim_string: true
 
par COil le 2008-09-28, taggé : mysql  parameter  propel 

[MySQL] Jointure externe - 110 view(s)

SELECT exforum.idforum AS id, exforum.datetimecreation AS date, 
    exusers.civilite AS civilite, exusers.nom AS nom, exusers.prenom AS prenom, exforum.sujet AS sujet, 
    count(tab2.id) AS count
    FROM exusers, exforum
        LEFT OUTER JOIN (
            SELECT id, idforum
        FROM exmessagesforum
    ) AS tab2 ON tab2.idforum = exforum.idforum
    WHERE exforum.iduser = exusers.iduser
    GROUP BY exforum.idforum, exforum.datetimecreation, exusers.civilite, exusers.nom, exusers.prenom, exforum.sujet
    LIMIT 0 , 4
 
par COil le 2008-09-28, taggé : join  mysql  query  select 

[MySQL] Modifier la valeur auto_increment d'une table - 89 view(s)

ALTER TABLE exbatch_commandes AUTO_INCREMENT = 5000;
 
par COil le 2008-09-28, taggé : auto  mysql  sequence 

[Propel] Recupérer la prochaine séquence d'une table - 186 view(s)

// Prochain numero de sequence
$filename .= '-'. myPropel::getNextSeq(ExbatchCommandesPeer::TABLE_NAME);
 

myPropel.class.php

/**
     * Fonction retournant la prochaine valeur autoincrement d'une table
     * 
     * @author Vernet Loic
     * @since  version - 28 févr. 2007
     */
    public static function getNextSeq($table_name)
    {
        $sql = "SHOW TABLE STATUS LIKE '$table_name'";
        $con = Propel::getConnection();
        $stmt = $con->createStatement();
        $rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
        $rs->first();
        return $rs->get('Auto_increment');
    }
 
par COil le 2008-09-28, taggé : mysql  propel  sequence  sql 
(1 commentaire)

[Propel] Récupérer quelques colonnes d'une table grâce a un Criteria - 112 view(s)

$c = new Criteria(); 
 
$c->clearSelectColumns()->addSelectColumn(ClientsPeer::IDCLIENT);
$c->addSelectColumn(ClientsPeer::NOM);
$rs = ClientsPeer::doSelectRS($c);        
$clientsWithId = myPropel::getTabFromRS($rs);
 

Fonction getTabFromRS:

    /**
     * Fonction retournant un tableau avec un ensemble de colonnes selectionnees
     * a l'aide d'un resultset
     * 
     * @author Vernet Loic
     * @since  2 janv. 2007
     */
    public static function getTabFromRS($rs, $one_row = false)
    {
        $tab = array();
        while ($rs->next()) {
            $tab[] = $rs->getRow();
        }
        return $one_row ? $tab[0] : $tab;
    }
 
par COil le 2008-09-28, taggé : criteria  mypropel  mysql  propel  sql 
Debug toolbar