Partage
  • Partager sur Facebook
  • Partager sur Twitter

UPDATE bdd avec foreach

    23 mai 2018 à 20:25:41

    Bonjour tout le monde,

    J'ai une fonction qui ajoute une liste de produits dans une table, chaque produit sur une ligne.

    Elle récupère un array d'un formulaire, c'est pour ca qu'il y a une boucle for :

    public function ajoutCommandeProduits($id ,$app ,$saisie){
                  
            $sql="INSERT INTO commande_produits (`id_prod`,`nom`,`options`,`quantite`,`prix`,`total`,`fraisdeport`,`grandtotal`) VALUES (:id_prod, :nom_prod, :options, :quantite, :prix, :total, :fraisdeport, :grandtotal)";
      
            $query = $app['db']->prepare($sql);
    
            $query->bindParam(':id_prod', $id_prod, PDO::PARAM_STR);
            $query->bindParam(':nom_prod', $nom, PDO::PARAM_STR);
            $query->bindParam(':options', $options, PDO::PARAM_STR);
            $query->bindParam(':quantite', $quantite, PDO::PARAM_STR);
            $query->bindParam(':prix', $prix, PDO::PARAM_STR);
            $query->bindParam(':total', $total, PDO::PARAM_STR);
            $query->bindParam(':fraisdeport', $fraisdeport, PDO::PARAM_STR);
            $query->bindParam(':grandtotal', $grandtotal, PDO::PARAM_STR);
    
            $length = count($saisie['nom_prod']);
     
            for($i=0;$i<$length;$i++) {
            $id_prod = $saisie['id_prod'][$i];
            $nom = $saisie['nom_prod'][$i];
            $options = $saisie['options'][$i];
            $quantite = $saisie['quantite'][$i];
            $prix = $saisie['prix'][$i];
            $total = $saisie['total'][$i];
            $fraisdeport = $saisie['fraisdeport'];
            $grandtotal = $saisie['grandtotal'];
            
    
            $query->execute();
            }
        }

    J'aurais aimé ajouter une autre fonction qui met à jour la liste des produits dans la meme table.

    J'ai essayé la fonction suivante mais je pense ne pas encore bien maitriser le foreach :

     public function updateCommandeProduits($id ,$app ,$saisie){
                  
            $sql="UPDATE commande_produits SET
             id_prod = :id_prod,
             nom = :nom_prod,
             options = :options,
             quantite = :quantite,
             prix = :prix,
             total = :total,
             fraisdeport = :fraisdeport,
             grandtotal = :grandtotal ";
      
            $query = $app['db']->prepare($sql);
    
            $query->bindParam(':id_prod', $id_prod, PDO::PARAM_STR);
            $query->bindParam(':nom_prod', $nom, PDO::PARAM_STR);
            $query->bindParam(':options', $options, PDO::PARAM_STR);
            $query->bindParam(':quantite', $quantite, PDO::PARAM_STR);
            $query->bindParam(':prix', $prix, PDO::PARAM_STR);
            $query->bindParam(':total', $total, PDO::PARAM_STR);
            $query->bindParam(':fraisdeport', $fraisdeport, PDO::PARAM_STR);
            $query->bindParam(':grandtotal', $grandtotal, PDO::PARAM_STR);
            
            foreach($saisie as $key => $value) {
            $id_prod = $saisie['id_prod'][$value];
            $nom = $saisie['nom_prod'][$value];
            $options = $saisie['options'][$value];
            $quantite = $saisie['quantite'][$value];
            $prix = $saisie['prix'][$value];
            $total = $saisie['total'][$value];
            $fraisdeport = $saisie['fraisdeport'][$value];
            $grandtotal = $saisie['grandtotal'][$value];
            
    
            $query->execute();
            }
        }

    J'ai cette erreur : Warning: Illegal offset type

    Est ce que quelqu'un voit ce qui cloche dans ma fonction?

    Merci pour votre aide!


    • Partager sur Facebook
    • Partager sur Twitter
      23 mai 2018 à 20:31:09

      Bonjour,

      On ne sait pas ce qu'il y a dans ton array, c'est un array multidimensionnel ?

      Mais déjà, je pense qu'il manque un where dans ta requête, sinon tu vas updater toutes les lignes.

      -
      Edité par philodick 23 mai 2018 à 20:34:16

      • Partager sur Facebook
      • Partager sur Twitter
        23 mai 2018 à 20:41:15

        Merci pour ta réponse philodick

        Oui c'est un array de ce type :  array('id_prod' => array('1', '6'), 'nom_prod' => array('american mix - Liquideo', 'Banane - Roykin'), 'options' => array('0mg', '0mg'), 'quantite' => array('1', '1'), 'prix' => array('4.9', '4.9'), 'total' => array('4.9', '4.9'), 'fraisdeport' => '5', 'grandtotal' => '14.8'))

        Là il n'y a que 2 valeurs pour chaque champ mais il peut y en avoir plus.

        Ah oui je vais rajouter WHERE id = :id ou qqch comme ca.

        Je suis un peu débutant n'ayons pas peur de le dire...Quelquechose clocherait dans mon foreach?

        -
        Edité par JulienProd 23 mai 2018 à 20:48:10

        • Partager sur Facebook
        • Partager sur Twitter
          23 mai 2018 à 20:56:01

          Bonsoir,

          Tout tes "bind" ne devrait-il pas être inclus dans ton foreach ? Sinon tu vas avoir des erreurs du faite qu'il ne connaisse pas tes variables.

          • Partager sur Facebook
          • Partager sur Twitter
            23 mai 2018 à 20:58:58

            Oui ton foreach n'est pas bon puisque tu devrais utiliser $key et $value et tu utilises $saisie à la place.

            Mais surtout, ton premier $value va $être un array contenant '1' et '6', le deuxième va contenir 'american mix - Liquideo' et  'Banane - Roykin'? etc...

            Avant d'aller plus loin, comment récupères-tu cet array ?

            Par contre je pense que le bind des variables est bon, puisqu'il est fait en paramètre.

            -
            Edité par philodick 23 mai 2018 à 21:04:34

            • Partager sur Facebook
            • Partager sur Twitter
              23 mai 2018 à 21:03:27

              Merci pour ta réponse Aurélien , j'ai essayé de bind après chaque foreach mais bon le probleme semble venir de mon foreach.

              Pour la question de philodick je récupère cet array via un formulaire , ce formulaire(hidden) est crée par une fonction js qui crée donc plusieurs champs de meme nom

              • Partager sur Facebook
              • Partager sur Twitter
                23 mai 2018 à 21:11:34

                Ok, donc $saisie est donc juste un $_POST ?

                Dans ce cas, je verrais plutôt une boucle for :

                $nb = count($saisie);
                  for($i=0;$i<$nb;$i++)
                	   {
                       $id_prod = $saisie['id_prod'][$i];
                       $nom = $saisie['nom_prod'][$i];
                       $options = $saisie['options'][$i];
                       $quantite = $saisie['quantite'][$i];
                       $prix = $saisie['prix'][$i];
                       $total = $saisie['total'][$i];
                       $fraisdeport = $saisie['fraisdeport'][$i];
                       $grandtotal = $saisie['grandtotal'][$i];
                        
                       $query->execute();
                       }



                • Partager sur Facebook
                • Partager sur Twitter
                  23 mai 2018 à 21:14:07

                  @philodick : de cette façon tu ne bind pas tes paramètres à chaque passage dans le for, non ?
                  • Partager sur Facebook
                  • Partager sur Twitter
                    23 mai 2018 à 21:19:38

                    Ils sont bindés avant, avec le nom de variable en fait. C'est la différence de base entre bindParam et bindValue.

                    Il suffit de redonner une nouvelle valeur aux variables à chaque tour et d'exécuter la requête.

                    -
                    Edité par philodick 23 mai 2018 à 21:21:24

                    • Partager sur Facebook
                    • Partager sur Twitter
                      23 mai 2018 à 21:28:29

                      J'ai copié ton for ca me met cette erreur : Notice: Uninitialized string offset: 1

                      in usersModels.php (line 196)

                      at usersModels->updateCommandeProduits(array('prenom' => 'Julien', 'userid' => '14', 'role' => ''), object(Application), array('id_prod' => array('1', '6'), 'nom_prod' => array('american mix - Liquideo', 'Banane - Roykin'), 'options' => array('0mg', '0mg'), 'quantite' => array('1', '1'), 'prix' => array('4.9', '4.9'), 'total' => array('4.9', '4.9'), 'fraisdeport' => '5', 'grandtotal' => '14.8'))in controllersUsers.php (line 92)

                      la ligne 196 est :

                       $fraisdeport = $saisie['fraisdeport'][$i];


                      J'avais essayé avec le meme for que ma première fonction ajoutCommande :

                       $length = count($saisie['nom_prod']);
                       
                              for($i=0;$i<$length;$i++) {
                              $id_prod = $saisie['id_prod'][$i];
                              $nom = $saisie['nom_prod'][$i];
                              $options = $saisie['options'][$i];
                              $quantite = $saisie['quantite'][$i];
                              $prix = $saisie['prix'][$i];
                              $total = $saisie['total'][$i];
                              $fraisdeport = $saisie['fraisdeport'];
                              $grandtotal = $saisie['grandtotal'];
                              
                      
                              $query->execute();
                      
                      
                              }

                      Mais ca update en ajoutant le dernier produit du panier plusieurs fois

                      Quelqu'un aurait une solution à ce probleme?

                      -
                      Edité par JulienProd 24 mai 2018 à 19:40:57

                      • Partager sur Facebook
                      • Partager sur Twitter
                        25 mai 2018 à 11:41:07

                        EN fait, je croyais que tu récupérais l'array directement d'un post,  là ta structure à l'air bien différente.
                        • Partager sur Facebook
                        • Partager sur Twitter
                          25 mai 2018 à 12:12:08

                          Bonjour, 
                          Pour moi je ne vois pas comment ça peux fonctionner si les valiables sont définit après le bindParam

                          -
                          Edité par coolswing 25 mai 2018 à 12:18:47

                          • Partager sur Facebook
                          • Partager sur Twitter
                            25 mai 2018 à 12:50:49

                            Bonjour,

                            Les variables sont passées par référence à bindParam, donc si elles n'existent pas PHP les crée et les assignent NULL.

                            • Partager sur Facebook
                            • Partager sur Twitter
                            le bienfait n'est jamais perdu
                              25 mai 2018 à 13:22:20

                              oui philodick l'array est récupéré d'un $_POST , bon à part le id_clent.

                              coolswing et WillyKouassi ,par rapport aux variables, la fonctions ajoutProduits fonctionne bien :

                              public function ajoutCommandeProduits($id ,$app ,$saisie){
                                      $user = $app['session']->get('user');
                                      $id_client = $user['userid'];
                              
                                      $sql="INSERT INTO commande_produits (`id_prod`,`nom`,`options`,`quantite`,`prix`,`total`,`fraisdeport`,`grandtotal` , `id_client`) VALUES (:id_prod, :nom_prod, :options, :quantite, :prix, :total, :fraisdeport, :grandtotal, :id_client)";
                                
                                      $query = $app['db']->prepare($sql);
                              
                                      $query->bindParam(':id_prod', $id_prod, PDO::PARAM_STR);
                                      $query->bindParam(':nom_prod', $nom, PDO::PARAM_STR);
                                      $query->bindParam(':options', $options, PDO::PARAM_STR);
                                      $query->bindParam(':quantite', $quantite, PDO::PARAM_STR);
                                      $query->bindParam(':prix', $prix, PDO::PARAM_STR);
                                      $query->bindParam(':total', $total, PDO::PARAM_STR);
                                      $query->bindParam(':fraisdeport', $fraisdeport, PDO::PARAM_STR);
                                      $query->bindParam(':grandtotal', $grandtotal, PDO::PARAM_STR);
                                      $query->bindParam(':id_client', $id_client, PDO::PARAM_STR);
                              
                              
                                          $length = count($saisie['nom_prod']);
                               
                                      for($i=0;$i<$length;$i++) {
                                      $id_prod = $saisie['id_prod'][$i];
                                      $nom = $saisie['nom_prod'][$i];
                                      $options = $saisie['options'][$i];
                                      $quantite = $saisie['quantite'][$i];
                                      $prix = $saisie['prix'][$i];
                                      $total = $saisie['total'][$i];
                                      $fraisdeport = $saisie['fraisdeport'];
                                      $grandtotal = $saisie['grandtotal'];
                                      $query->execute();
                                      }
                              
                                  }

                              Alors je m'étais dit que la fonction updateProduits allait marchait également ainsi en modifiant la requète( je suis un peu novice je sais...).

                              La fonction update ne m'ajoute que le dernier produit du panier plusieurs fois...

                              • Partager sur Facebook
                              • Partager sur Twitter
                                25 mai 2018 à 13:30:15

                                @JulienProd, je répondais à CoolSwing

                                Tu n'as pas de WHERE dans ton UPDATE ? Ta table va contenir les valeurs du dernier tour de boucle.

                                -
                                Edité par WillyKouassi 25 mai 2018 à 13:30:31

                                • Partager sur Facebook
                                • Partager sur Twitter
                                le bienfait n'est jamais perdu
                                  25 mai 2018 à 13:33:17

                                  Ah ok.

                                  J'ai un WHERE id_client = :id_client

                                   $sql="UPDATE commande_produits SET
                                           id_prod = :id_prod,
                                           nom = :nom_prod,
                                           options = :options,
                                           quantite = :quantite,
                                           prix = :prix,
                                           total = :total,
                                           fraisdeport = :fraisdeport,
                                           grandtotal = :grandtotal,
                                           id_client = :id_client
                                           WHERE id_client = :id_client ";

                                  Peut etre mon where n'est pas bon?

                                  -
                                  Edité par JulienProd 25 mai 2018 à 13:33:56

                                  • Partager sur Facebook
                                  • Partager sur Twitter
                                    25 mai 2018 à 13:53:59

                                    J'ai modifié la fonction :

                                     public function updateCommandeProduits($id_client ,$app ,$saisie){
                                            $user = $app['session']->get('user');
                                            $id_client = $user['userid'];
                                                  
                                            $sql="UPDATE commande_produits SET
                                             id_prod = :id_prod,
                                             nom = :nom_prod,
                                             options = :options,
                                             quantite = :quantite,
                                             prix = :prix,
                                             total = :total,
                                             fraisdeport = :fraisdeport,
                                             grandtotal = :grandtotal,
                                             
                                             WHERE 
                                             id_prod = :id_prod,
                                             nom = :nom_prod,
                                             options = :options,
                                             quantite = :quantite,
                                             prix = :prix,
                                             total = :total,
                                             fraisdeport = :fraisdeport,
                                             grandtotal = :grandtotal";
                                    
                                             $query = $app['db']->prepare($sql);
                                    
                                            $query->bindParam(':id_prod', $id_prod, PDO::PARAM_STR);
                                            $query->bindParam(':nom_prod', $nom, PDO::PARAM_STR);
                                            $query->bindParam(':options', $options, PDO::PARAM_STR);
                                            $query->bindParam(':quantite', $quantite, PDO::PARAM_STR);
                                            $query->bindParam(':prix', $prix, PDO::PARAM_STR);
                                            $query->bindParam(':total', $total, PDO::PARAM_STR);
                                            $query->bindParam(':fraisdeport', $fraisdeport, PDO::PARAM_STR);
                                            $query->bindParam(':grandtotal', $grandtotal, PDO::PARAM_STR);
                                            $query->bindParam(':id_client', $id_client, PDO::PARAM_STR);
                                    
                                             $length = count($saisie['nom_prod']);
                                     
                                            for($i=0;$i<$length;$i++) {
                                            $id_prod = $saisie['id_prod'][$i];
                                            $nom = $saisie['nom_prod'][$i];
                                            $options = $saisie['options'][$i];
                                            $quantite = $saisie['quantite'][$i];
                                            $prix = $saisie['prix'][$i];
                                            $total = $saisie['total'][$i];
                                            $fraisdeport = $saisie['fraisdeport'];
                                            $grandtotal = $saisie['grandtotal'];
                                            $query->execute();
                                            }
                                             
                                        }

                                    J'ai une erreur de syntaxe SQL , j'ai fouillé un peu sur le net mais je trouve pas l'erreur...

                                    • Partager sur Facebook
                                    • Partager sur Twitter
                                      25 mai 2018 à 13:57:09

                                      Logiquement ceci devrait suffire :

                                      $sql="UPDATE commande_produits SET
                                      id_prod = :id_prod,
                                      nom = :nom_prod,
                                      options = :options,
                                      quantite = :quantite,
                                      prix = :prix,
                                      total = :total,
                                      fraisdeport = :fraisdeport,
                                      grandtotal = :grandtotal
                                      WHERE id_client = :id_client ";



                                      -
                                      Edité par philodick 25 mai 2018 à 13:57:31

                                      • Partager sur Facebook
                                      • Partager sur Twitter
                                        25 mai 2018 à 14:01:45

                                        Ben ca m'update que le dernier produit plusieurs fois...

                                        Peut etre que j'ai mal déclaré des variables?

                                        Ou l'erreur pourrait venir de mon controller?

                                        • Partager sur Facebook
                                        • Partager sur Twitter
                                          25 mai 2018 à 14:06:22

                                          Mais tu as quoi dans id_prod ? parce que si tu veux boucler sur plusieurs valeurs il faudrait en effet aussi le mettre dans le where :

                                          $sql="UPDATE commande_produits SET
                                          nom = :nom_prod,
                                          options = :options,
                                          quantite = :quantite,
                                          prix = :prix,
                                          total = :total,
                                          fraisdeport = :fraisdeport,
                                          grandtotal = :grandtotal
                                          WHERE id_client = :id_client AND id_prod = :id_prod";



                                          • Partager sur Facebook
                                          • Partager sur Twitter
                                            25 mai 2018 à 14:07:33

                                            Oui toutes les variables contiennent plusieurs valeurs
                                            • Partager sur Facebook
                                            • Partager sur Twitter
                                              25 mai 2018 à 14:13:52

                                              oui effectivement ce sont tous des array sauf id_client , fraisdeport et grandtotal
                                              • Partager sur Facebook
                                              • Partager sur Twitter
                                                25 mai 2018 à 15:34:47

                                                WillyKouassi a écrit:

                                                Bonjour,

                                                Les variables sont passées par référence à bindParam, donc si elles n'existent pas PHP les crée et les assignent NULL.


                                                autant pour moi effectivement.

                                                -
                                                Edité par coolswing 25 mai 2018 à 15:41:28

                                                • Partager sur Facebook
                                                • Partager sur Twitter
                                                  25 mai 2018 à 16:15:24

                                                  JulienProd a écrit:

                                                  oui effectivement ce sont tous des array sauf id_client , fraisdeport et grandtotal


                                                  Mais alors il ne faut pas les redéclarer dans la boucle, il ne sont pas dans l'array. Tu les définis au début et c'est tout.
                                                  • Partager sur Facebook
                                                  • Partager sur Twitter
                                                    25 mai 2018 à 16:15:44

                                                    Bonjour,

                                                    Il te faut un tableau associatif qui reprend la stucture de ta table :

                                                    $ligne = array('id_prod' => xxx, 'nom_prod => xxx, 'options' => xxx ........etc)

                                                    Ensuite tu empiles chaque ligne dans un array.

                                                    $saisie[] = $ligne

                                                    Pour finir cette boucle devrait suffire :

                                                    foreach($saisie as $key => $element) {
                                                      foreach($element as $k => $e) {
                                                        $query->bindParam(':'.$k, $e);
                                                      }
                                                      $query->execute();
                                                    }

                                                    -
                                                    Edité par psyckyo 25 mai 2018 à 19:41:06

                                                    • Partager sur Facebook
                                                    • Partager sur Twitter
                                                      25 mai 2018 à 18:50:23

                                                      Donc en résumé, il suffirait de les sortir de la boucle :

                                                      $id_client = $saisie['id_client'];
                                                      $fraisdeport = $saisie['fraisdeport'];
                                                      $grandtotal = $saisie['grandtotal']; 
                                                        for($i=0;$i<$length;$i++) {
                                                             $id_prod = $saisie['id_prod'][$i];
                                                             $nom = $saisie['nom_prod'][$i];
                                                             $options = $saisie['options'][$i];
                                                             $quantite = $saisie['quantite'][$i];
                                                             $prix = $saisie['prix'][$i];
                                                             $total = $saisie['total'][$i];
                                                             $query->execute();
                                                             }



                                                      -
                                                      Edité par philodick 25 mai 2018 à 18:51:06

                                                      • Partager sur Facebook
                                                      • Partager sur Twitter
                                                        25 mai 2018 à 21:05:11

                                                        Ahh ca marche mieux! Par contre ca m'ajoute les produits en plus des autres, ca me les update pas...

                                                        Je poste ma fonction telle qu'elle est , j'ai ptet encore merdé quelquepart...

                                                        public function updateCommandeProduits($id_client ,$app ,$saisie){
                                                                $user = $app['session']->get('user');
                                                                $id_client = $user['userid'];
                                                                      
                                                                $sql="UPDATE commande_produits SET
                                                                id_prod = :id_prod,
                                                                nom = :nom_prod,
                                                                options = :options,
                                                                quantite = :quantite,
                                                                prix = :prix,
                                                                total = :total,
                                                                fraisdeport = :fraisdeport,
                                                                grandtotal = :grandtotal
                                                                WHERE  id_prod = :id_prod AND nom = :nom_prod AND options = :options AND quantite = :quantite AND prix = :prix AND total = :total";
                                                        
                                                                 $query = $app['db']->prepare($sql);
                                                        
                                                                $query->bindParam(':id_prod', $id_prod, PDO::PARAM_STR);
                                                                $query->bindParam(':nom_prod', $nom, PDO::PARAM_STR);
                                                                $query->bindParam(':options', $options, PDO::PARAM_STR);
                                                                $query->bindParam(':quantite', $quantite, PDO::PARAM_STR);
                                                                $query->bindParam(':prix', $prix, PDO::PARAM_STR);
                                                                $query->bindParam(':total', $total, PDO::PARAM_STR);
                                                                $query->bindParam(':fraisdeport', $fraisdeport, PDO::PARAM_STR);
                                                                $query->bindParam(':grandtotal', $grandtotal, PDO::PARAM_STR);
                                                                $query->bindParam(':id_client', $id_client, PDO::PARAM_STR);
                                                        
                                                                 $length = count($saisie['nom_prod']);
                                                                
                                                                $fraisdeport = $saisie['fraisdeport'];
                                                                $grandtotal = $saisie['grandtotal'];
                                                                 for($i=0;$i<$length;$i++) {
                                                               $id_prod = $saisie['id_prod'][$i];
                                                               $nom = $saisie['nom_prod'][$i];
                                                               $options = $saisie['options'][$i];
                                                               $quantite = $saisie['quantite'][$i];
                                                               $prix = $saisie['prix'][$i];
                                                               $total = $saisie['total'][$i];
                                                               $query->execute();
                                                               }
                                                                 
                                                            }



                                                        • Partager sur Facebook
                                                        • Partager sur Twitter
                                                          25 mai 2018 à 21:15:23

                                                          Ta requête n'a pas de sens, tu as la même chose dans le SET et le WHERE. En résumé, tu mets une valeur dans les colonnes qui ont déjà la même valeur...

                                                          Pour les données ajoutées au lieu de modifiées, je n'ai jamais vu ça avec un UPDATE.

                                                          • Partager sur Facebook
                                                          • Partager sur Twitter

                                                          UPDATE bdd avec foreach

                                                          × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                                                          × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
                                                          • Editeur
                                                          • Markdown