Partage
  • Partager sur Facebook
  • Partager sur Twitter

INSERT INTO d'un tableau vers une BDD

Sujet résolu
    2 avril 2024 à 15:18:31

    Bonjour,

    Je cale depuis plusieurs jours sur un problème d'insertion de ma table HTML vers ma BDD MySql.

    L'idée étant d'enregistrer une ligne que si la quantité est renseigné.

    Pourriez vous me guider vers la solution.

    Voici mon code:

              <div class="tableauCmd" id="main">
                    <section>
                        <table id="tableau">
                            <thead>
                                <tr>
                                    <th width=20%>Désignation</th>
                                    <th width=20%>Code article</th>
                                    <th width=40%>Couleur</th>
                                    <th width=20%>Code couleur</th>
                                    <th width=60%>U.V.C....................................</th>
                                    <th width=30%>Taille</th>
                                    <th width=30%>Quantité</th>
                                </tr>
                            </thead>
                            <tbody>
    			<?php
    
    try {
        $bdd = new PDO('mysql:host=localhost;dbname=xxxx;charset=utf8', '', '');
    } catch (Exception $e) {
        die('Erreur : ' . $e->getMessage());
    }
    
    $query = $bdd->prepare('SELECT ART_CODE,ART_DESIGN,COL_LIBELLE,COL_CODE,ART_UVC,ART_TAILLE FROM ARTICLES,COLORS WHERE ART_COL=COL_CODE AND ART_CODE="' . $_POST['article'] . '" ORDER BY ART_UVC');
    $query->execute();
    while ($data = $query->fetch()) {
    ?>
        <tr>
        <div>
            <td><input type="text" class="col" name="designation" value="<?php echo $data['ART_DESIGN']; ?>"></td>
            <td><input type="text" class="col" name="codearticle" value="<?php echo $data['ART_CODE']; ?>"></td>
            <td><input type="text" class="col" name="colorislibelle" value="<?php echo $data['COL_LIBELLE']; ?>"></td>
            <td><input type="text" class="col" name="coloriscode" value="<?php echo $data['COL_CODE']; ?>"></td>
            <td><input type="text" class="col" name="uvc" value="<?php echo $data['ART_UVC']; ?>"></td>
            <td><input type="text" class="col" name="taillearticle" value="<?php echo $data['ART_TAILLE']; ?>"></td>
            <td><input type="text" class="col"  name="qty"></td>
            </div>
        </tr>
    <?php
    }
    ?>
                            </tbody>
                        </table>

     Pour la partie INSERT INTO, c'est ici que j'ai mon soucis car seule la dernière ligne du tableau s’insère alors que la quantité est à 0

    while(isset($_POST['codearticle'][++$i]))
    if(isset($_POST["codearticle"])) 
    { 
         if($_POST["qty"] != 0) {
    {
    {
    
        try {
            $dbco = new PDO("mysql:host=localhost;dbname=simag_prod", 'root', 'root');
            $dbco->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql3 = "INSERT INTO CMD_LIGNE(LIG_NUM_CMD,LIG_ART_CODE,LIG_ART_LIBELLE,LIG_ART_COLOR,LIG_ART_TAILLE,LIG_UVC,
            LIG_ART_QTY,LIG_DATE_CREATE) VALUES ('" . $_POST['CmdNum'] . "' , '" . $_POST['codearticle'] . "' , '" . $_POST['designation'] . "' ,
            '" . $_POST['colorislibelle'] . "' , '" . $_POST['taillearticle'] . "' , '" . $_POST['uvc'] . "' ,
            '" . $_POST['qty'] . "' ,'" . date('y-m-d h:i:s')  . "')";
            $dbco->exec($sql3);
            var_dump($sql3);
            var_dump($_POST['qty']);
        } catch (PDOException $x) {
            echo "Erreur : " . $x->getMessage();
        }
    }}}
    }



    Je suis quasiment certain que le problème provient des conditions

    Merci beaucoup par avance



    • Partager sur Facebook
    • Partager sur Twitter
      2 avril 2024 à 19:20:39

      Bonjour,

      Il va falloir préparer tes requêtes pour éviter les injections sql (sécurité)

      exec n'est pas fait pour ce genre d'insertion, il faut utiliser prepare + execute ou prepare + bindparam/bindvalue + execute

      il manque les accolades a ton while. Apprends à bien indenter ton code, cela t'aidera

      enfin tu peux sortir les lignes 9 et 10 pour la connexion à l'extérieur de ta boucle while

      ah j'allais oublier, avec ce code, seul la dernière ligne de ton tableau sera renseigner.

      • Partager sur Facebook
      • Partager sur Twitter
        2 avril 2024 à 20:13:07

        Bonsoir,

        J'ai revu ma requête en fonction de vos remarques (merci beaucoup), et en effet, seule la dernière ligne s'insère, mais là....je cale.

        Pouvez vous me mettre sur la bonne route svp

        Voici le code rectifié

                <?php
                    $servname = "localhost"; $dbname = "xxxx"; $user = "xxxx"; $pass = "xxxx";
              
                    try{
                        $dbco = new PDO("mysql:host=$servname;dbname=$dbname", $user, $pass);
                        $dbco->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                        
                        $num = $_POST['CmdNum'];
                        $codeart = $_POST['codearticle'];
                        $artlibelle = $_POST['designation'];
                        $color = $_POST['colorislibelle'];
                        $taille = $_POST['taillearticle'];
                        $uvc = $_POST['uvc'];
                        $qty = $_POST['qty'];
                        $create = date('y-m-d h:i:s');
                      
                        //$sth appartient à la classe PDOStatement
                        $sth = $dbco->prepare("
                        INSERT INTO CMD_LIGNE(LIG_NUM_CMD,LIG_ART_CODE,LIG_ART_LIBELLE,LIG_ART_COLOR,LIG_ART_TAILLE,LIG_UVC,
                        LIG_ART_QTY,LIG_DATE_CREATE)
                            VALUES (:numcmd, :codearticle, :artlibelle, :artcolor, :arttaille, :uvc, :quantite, :creation)
                        ");
                        $sth->execute(array(
                                            ':numcmd' => $num,
                                            ':codearticle' => $codeart,
                                            ':artlibelle' => $artlibelle,
                                            ':artcolor' => $color,
                                            ':arttaille' => $taille,
                                            ':uvc' => $uvc,
                                            ':quantite' => $qty,
                                            ':creation' => $create));
                        echo "Entrée ajoutée dans la table";
                    }
                          
                    catch(PDOException $e){
                        echo "Erreur : " . $e->getMessage();
                    }
                ?>



        • Partager sur Facebook
        • Partager sur Twitter
          2 avril 2024 à 20:45:46

          C'est déjà mieux.

          il y a encore des choses à revoir.

          Pour le tableau et bien avoir toutes les lignes de ce dernier, il y a plusieurs possibilités.

          - mettre le name de ton input en "tableau"

          <input name="designation[]">

          - ajouter un nom unique (soit via le code article ou un id)

          <input name="designation_<?= $code_article;?>" >

          https://openclassrooms.com/forum/sujet/insertion-plusieurs-lignes-dans-bdd-49147

          Tu peux t'inspirer de ce topic (juste la partie structure et gestion - ne pas pendre les fonctions mysql_* qui sont supprimées)


          • Partager sur Facebook
          • Partager sur Twitter
            2 avril 2024 à 21:12:17

            Hello,

            Il y a un point que je ne comprends pas, j'ai modifié cette partie:

                <tr>
                <div>
                    <td><input type="text" class="col" name="designation[]" value="<?php echo $data['ART_DESIGN']; ?>"></td>
                    <td><input type="text" class="col" name="codearticle[]" value="<?php echo $data['ART_CODE']; ?>"></td>
                    <td><input type="text" class="col" name="colorislibelle[]" value="<?php echo $data['COL_LIBELLE']; ?>"></td>
                    <td><input type="text" class="col" name="coloriscode[]" value="<?php echo $data['COL_CODE']; ?>"></td>
                    <td><input type="text" class="col" name="uvc[]" value="<?php echo $data['ART_UVC']; ?>"></td>
                    <td><input type="text" class="col" name="taillearticle[]" value="<?php echo $data['ART_TAILLE']; ?>"></td>
                    <td><input type="text" class="col"  name="qty[]"></td>
                    </div>
                </tr>

            et ajouté ceci à cette partie:  $codeart = $_POST['codearticle'];
                                 for($i=0;$i<$codeart;$i++)
                              {

                            $num = $_POST['CmdNum'];
                            $codeart = $_POST['codearticle'][$i];
                            $artlibelle = $_POST['designation'][$i];
                            $color = $_POST['colorislibelle'][$i];
                            $taille = $_POST['taillearticle'][$i];
                            $uvc = $_POST['uvc'][$i];
                            $qty = $_POST['qty'][$i];
                            $create = date('y-m-d h:i:s');
            
                            $codeart = $_POST['codearticle'];
                                 for($i=0;$i<$codeart;$i++)
                              {
            
                            //$sth appartient à la classe PDOStatement
                            $sth = $dbco->prepare("
                            INSERT INTO CMD_LIGNE(LIG_NUM_CMD,LIG_ART_CODE,LIG_ART_LIBELLE,LIG_ART_COLOR,LIG_ART_TAILLE,LIG_UVC,
                            LIG_ART_QTY,LIG_DATE_CREATE)
                                VALUES (:numcmd, :codearticle, :artlibelle, :artcolor, :arttaille, :uvc, :quantite, :creation)
                            ");
                            $sth->execute(array(
                                                ':numcmd' => $num,
                                                ':codearticle' => $codeart,
                                                ':artlibelle' => $artlibelle,
                                                ':artcolor' => $color,
                                                ':arttaille' => $taille,
                                                ':uvc' => $uvc,
                                                ':quantite' => $qty,
                                                ':creation' => $create));
            
                            echo "Entrée ajoutée dans la table";
                        }
                    }
                        
                        catch(PDOException $e){
                            echo "Erreur : " . $e->getMessage();
                        }


            MAis j'obtiens les erreurs suivates:

            Warning: Undefined variable $i in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 9
            
            Warning: Undefined array key "" in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 9
            
            Warning: Undefined variable $i in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 10
            
            Warning: Undefined array key "" in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 10
            
            Warning: Undefined variable $i in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 11
            
            Warning: Undefined array key "" in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 11
            
            Warning: Undefined variable $i in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 12
            
            Warning: Undefined array key "" in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 12
            
            Warning: Undefined variable $i in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 13
            
            Warning: Undefined array key "" in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 13
            
            Warning: Undefined variable $i in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 14
            
            Warning: Undefined array key "" in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 14
            
            Warning: Array to string conversion in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 27
            Erreur : SQLSTATE[23000]: Integrity constraint violation: 1048 Le champ 'LIG_UVC' ne peut être vide (null) 

            Alors que je suis certain que le champ LIG_UVC est bien présent car il s'affiche dans le tableau


            • Partager sur Facebook
            • Partager sur Twitter
              2 avril 2024 à 21:29:57

              <?php
              //$sth appartient à la classe PDOStatement
              $sth = $dbco->prepare("
              INSERT INTO CMD_LIGNE(LIG_NUM_CMD,LIG_ART_CODE,LIG_ART_LIBELLE,LIG_ART_COLOR,LIG_ART_TAILLE,LIG_UVC,
              LIG_ART_QTY,LIG_DATE_CREATE)
                  VALUES (:numcmd, :codearticle, :artlibelle, :artcolor, :arttaille, :uvc, :quantite, NOW())
              ");
              for($i=0;$i<$codeart;$i++)
              {
              
                  $num = $_POST['CmdNum'];
                  $codeart = $_POST['codearticle'][$i];
                  $artlibelle = $_POST['designation'][$i];
                  $color = $_POST['colorislibelle'][$i];
                  $taille = $_POST['taillearticle'][$i];
                  $uvc = $_POST['uvc'][$i];
                  $qty = $_POST['qty'][$i];
              
                  $codeart = $_POST['codearticle'];
              
                  $sth->execute(array(
                                      ':numcmd' => $num,
                                      ':codearticle' => $codeart,
                                      ':artlibelle' => $artlibelle,
                                      ':artcolor' => $color,
                                      ':arttaille' => $taille,
                                      ':uvc' => $uvc,
                                      ':quantite' => $qty));
               
                  }
              }

              ceci sera déjà mieux

              ton code article est toujours le même ?

              sur la page de traitement $codeart doit correspondre au nombre de ligne de ton tableau donc soit tu passes se paramètre via un champ caché (input hidden) ou tu le récupères via une requête

              -
              Edité par Aurélien10! 2 avril 2024 à 21:30:52

              • Partager sur Facebook
              • Partager sur Twitter
                2 avril 2024 à 23:45:23

                Bonjour,

                Nette amélioration, mais une idée pour que je n'enregistre que les lignes dont la quantité est sup à 0, car j'enregistre toutes les lignes y compris celles à 0

                            //$sth appartient à la classe PDOStatement
                            $sth = $dbco->prepare("
                                INSERT INTO CMD_LIGNE(LIG_NUM_CMD,LIG_ART_CODE,LIG_ART_LIBELLE,LIG_ART_COLOR,LIG_ART_TAILLE,LIG_UVC,
                                LIG_ART_QTY,LIG_DATE_CREATE)
                                    VALUES (:numcmd, :codearticle, :artlibelle, :artcolor, :arttaille, :uvc, :quantite, :creation)
                                ");
                
                                $codeart = $_POST['codearticle'];
                                for ($i = 0; $i < $codeart; $i++) {
                
                                $num = $_POST['CmdNum'];
                                $codeart = $_POST['codearticle'][$i];
                                $artlibelle = $_POST['designation'][$i];
                                $color = $_POST['colorislibelle'][$i];
                                $taille = $_POST['taillearticle'][$i];
                                $uvc = $_POST['uvc'][$i];
                                $qty = $_POST['qty'][$i];
                                $create = date('y-m-d h:i:s');
                
                                $sth->execute(array(
                                    ':numcmd' => $num,
                                    ':codearticle' => $codeart,
                                    ':artlibelle' => $artlibelle,
                                    ':artcolor' => $color,
                                    ':arttaille' => $taille,
                                    ':uvc' => $uvc,
                                    ':quantite' => $qty,
                                    ':creation' => $create
                                ));
                
                                echo "Entrée ajoutée dans la table";
                            }
                        } catch (PDOException $e) {
                            echo "Erreur : " . $e->getMessage();
                        }
                        ?>


                Merci beaucoup pour ton aide

                • Partager sur Facebook
                • Partager sur Twitter
                  2 avril 2024 à 23:59:59

                  comme tu le faisais sur ton 1er code, 

                  tu testes si qty est supérieur à 1 alors tu fais le executes

                  $create est inutile avec le code que je t'ai fournis. voir même le faire directement comme valeaur par défaut dans la BDD

                  • Partager sur Facebook
                  • Partager sur Twitter
                    3 avril 2024 à 8:22:47

                    Bonjour,

                    Malgré l'ajout de la condition, cela continue à enregistrer toutes les lignes

                                //$sth appartient à la classe PDOStatement
                                $sth = $dbco->prepare("
                                    INSERT INTO CMD_LIGNE(LIG_NUM_CMD,LIG_ART_CODE,LIG_ART_LIBELLE,LIG_ART_COLOR,LIG_ART_TAILLE,LIG_UVC,
                                    LIG_ART_QTY,LIG_DATE_CREATE)
                                        VALUES (:numcmd, :codearticle, :artlibelle, :artcolor, :arttaille, :uvc, :quantite, :creation)
                                    ");
                                    var_dump($sth);
                    
                                    if($_POST["qty"] != 0) {
                    
                                    $codeart = $_POST['codearticle'];
                                    for ($i = 0; $i < $codeart; $i++) {
                    
                                    $num = $_POST['CmdNum'];
                                    $codeart = $_POST['codearticle'][$i];
                                    $artlibelle = $_POST['designation'][$i];
                                    $color = $_POST['colorislibelle'][$i];
                                    $taille = $_POST['taillearticle'][$i];
                                    $uvc = $_POST['uvc'][$i];
                                    $qty = $_POST['qty'][$i];
                                    $create = date('y-m-d h:i:s');
                    
                                    $sth->execute(array(
                                        ':numcmd' => $num,
                                        ':codearticle' => $codeart,
                                        ':artlibelle' => $artlibelle,
                                        ':artcolor' => $color,
                                        ':arttaille' => $taille,
                                        ':uvc' => $uvc,
                                        ':quantite' => $qty,
                                        ':creation' => $create
                                    ));
                    
                    
                                    echo "Entrée ajoutée dans la table";
                                }}
                            } catch (PDOException $e) {
                                echo "Erreur : " . $e->getMessage();
                            }


                    Je continue à chercher, merci encore pour votre aide

                    • Partager sur Facebook
                    • Partager sur Twitter
                      3 avril 2024 à 15:06:22

                      C'est dans la boucle qu'il faut tester.

                      Notamment ta ligne 20 dans le dernier code.

                      • Partager sur Facebook
                      • Partager sur Twitter
                        3 avril 2024 à 15:22:55

                        J'ai finis par trouver la solution pour enregistrer que les lignes avec des quantités > 0, en modifiant la condition:(

                        if ($qty !== 0 AND $qty !=NULL ) {)

                                    $sth = $dbco->prepare("
                                        INSERT INTO CMD_LIGNE(LIG_NUM_CMD,LIG_ART_CODE,LIG_ART_LIBELLE,LIG_ART_COLOR,LIG_ART_TAILLE,LIG_UVC,
                                        LIG_ART_QTY,LIG_DATE_CREATE)
                                            VALUES (:numcmd, :codearticle, :artlibelle, :artcolor, :arttaille, :uvc, :quantite, :creation) ");
                        
                        
                                    $codeart = $_POST['codearticle'];
                                    for ($i = 0; $i < $codeart; $i++) {
                        
                        
                                            $num = $_POST['CmdNum'];
                                            $codeart = $_POST['codearticle'][$i];
                                            $artlibelle = $_POST['designation'][$i];
                                            $color = $_POST['colorislibelle'][$i];
                                            $taille = $_POST['taillearticle'][$i];
                                            $uvc = $_POST['uvc'][$i];
                                            $qty = $_POST['qty'][$i];
                                            $create = date('y-m-d h:i:s');
                        
                                            if ($qty !== 0 AND $qty !=NULL ) {
                                                
                                            $sth->execute(array(
                                                ':numcmd' => $num,
                                                ':codearticle' => $codeart,
                                                ':artlibelle' => $artlibelle,
                                                ':artcolor' => $color,
                                                ':arttaille' => $taille,
                                                ':uvc' => $uvc,
                                                ':quantite' => $qty,
                                                ':creation' => $create
                                            ));
                                            //echo "Entrée ajoutée dans la table";
                                        }
                                    }

                        Mais je ne comprends toujours pas pourquoi ces messages

                        Warning: Undefined array key 15 in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 23
                        
                        Warning: Undefined array key 15 in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 24
                        
                        Warning: Undefined array key 15 in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 25
                        
                        Warning: Undefined array key 15 in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 26
                        
                        Warning: Undefined array key 15 in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 27
                        
                        Warning: Undefined array key 15 in C:\wamp64\www\simag_prod\securise\requete\cmd_client\ztest.php on line 28

                        -
                        Edité par DominiqueSimon5 3 avril 2024 à 20:56:03

                        • Partager sur Facebook
                        • Partager sur Twitter
                          5 avril 2024 à 9:27:39

                          Bonjour,

                          Visiblement il y a un index en trop ; faudrait vérifier 

                          $i < $codeart

                          D'autant que sans avoir trop suivi l'affaire 

                          $codeart = $_POST['codearticle'];

                          Ça reste un tableau, il est jamais compté non ?

                          Genre :

                          for($i=0;$i<count($_POST['codearticle']);$i++)





                           

                          -
                          Edité par GBNet 5 avril 2024 à 9:31:03

                          • Partager sur Facebook
                          • Partager sur Twitter
                            5 avril 2024 à 11:28:12

                            Bonjour,

                            Pour quelqu'un "qui n'a pas suivi l'affaire", vous êtes un génie...

                            En effet, votre proposition est parfaite, je n'est plus aucune erreur.

                            Franchement merci beaucoup.

                            J'ai une dernière question  qui n'a rien à voir avec mon problème....Je suis à la recherche d'un article qui me donnerais des idées sur arborescence et sur les bonnes pratiques quant à l'arborescence d'un site, je m'explique:

                            Comment stocker les requêtes de connexion (.INI), les requêtes select et autres.....

                            Je viens du monde Windev et donc en server local entreprise, et je me rends compte que le monde du web est plus complexe.

                            Merci en tout cas

                            • Partager sur Facebook
                            • Partager sur Twitter
                              5 avril 2024 à 18:21:49

                              je te conseil de poster un nouveau sujet et de passer celui-ci en résolu.

                              Piste, Modèle MVC (pour la struture d'un site) et je pense que tu parles de "log", si oui alors il doit y avoir des choses toutes faites.

                              • Partager sur Facebook
                              • Partager sur Twitter

                              INSERT INTO d'un tableau vers une BDD

                              × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                              • Editeur
                              • Markdown