IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

PHP & Base de données Discussion :

Récupérer une valeur de liste déroulante [MySQL]


Sujet :

PHP & Base de données

  1. #1
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2018
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Septembre 2018
    Messages : 13
    Par défaut Récupérer une valeur de liste déroulante
    Bonsoir

    J'ai une liste déroulante sur ma page qui est rempli grace à une de mes table de base donnée .
    Je voudrai quand je chosi un champ de ma liste déroulante cela maffiche un tableau par rapport a ce choix.
    En faite, il faut juste que je recupere la valeur pour ensuite la mettre dans une requete qui afficha ma table.
    Mais je n'arrive pas a recuperer celle-ci, il s'affice um message:

    Notice: Undefined index: choix in C:\xampp\htdocs\pdf_export\index.php on line 8, mais j'ai déclaré dans la ligne: 89
    Voila mon code

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
     
    <?php  
     function fetch_data()  
     {  
          $output = '';  
          $conn = mysqli_connect("localhost", "root", "", "tut");  
     
          	     $ligne_ok = mysqli_query($conn, 'SELECT * FROM pdf_export where age = \''.$_POST['choix'].'\'');
     
     
     
    	  while($row = mysqli_fetch_array($ligne_ok))  
          {       
          $output .= '<tr>  
                              <td>'.$row["id"].'</td>  
                              <td>'.$row["name"].'</td>  
                              <td>'.$row["age"].'</td>  
                              <td>'.$row["email"].'</td>  
                         </tr>  
                              ';  
          }  
          return $output;  
     }  
     if(isset($_POST["generate_pdf"]))  
     {  
          require_once('tcpdf/tcpdf.php');  
          $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);  
          $obj_pdf->SetCreator(PDF_CREATOR);  
          $obj_pdf->SetTitle("Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP");  
          $obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);  
          $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));  
          $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));  
          $obj_pdf->SetDefaultMonospacedFont('helvetica');  
          $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);  
          $obj_pdf->SetMargins(PDF_MARGIN_LEFT, '10', PDF_MARGIN_RIGHT);  
          $obj_pdf->setPrintHeader(false);  
          $obj_pdf->setPrintFooter(false);  
          $obj_pdf->SetAutoPageBreak(TRUE, 10);  
          $obj_pdf->SetFont('helvetica', '', 11);  
          $obj_pdf->AddPage();  
          $content = '';  
          $content .= '  
          <h4 align="center">Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP</h4><br /> 
          <table border="1" cellspacing="0" cellpadding="3">  
               <tr>  
                    <th width="5%">Id</th>  
                    <th width="30%">Name</th>  
                    <th width="15%">Age</th>  
                    <th width="50%">Email</th>  
               </tr>  
          ';  
          $content .= fetch_data();  
          $content .= '</table>';  
          $obj_pdf->writeHTML($content);  
          $obj_pdf->Output('file.pdf', 'I');  
     }
     
     ?>  
     <!DOCTYPE html>  
     <html>  
          <head>  
               <title>SoftAOX | Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP</title>  
               <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />            
          </head>  
     
     
     
          <body>  
               <br />
               <div class="container">  
                    <h4 align="center"> Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP</h4><br />  
                    <div class="table-responsive">  
                    	<div class="col-md-12" align="right">
                         <form method="post">  
                              <input type="submit" name="generate_pdf" class="btn btn-success" value="Generate PDF" />  
    						  	 <br/>
    <?php
        //Include database configuration file
        //include('dbConfig.php');
        $db = mysqli_connect("localhost", "root", "", "tut");  
     
        //Get all country data
         $query = $db->query("SELECT * FROM  pdf_export ");
     
        //Count total number of rows
        $rowCount = $query->num_rows;
        ?>
     
        <select name="choix" id="choix"  class="form-control" >
            <option value="">Show All</option>
            <?php
            if($rowCount > 0){
     
                while($row = $query->fetch_assoc()){ 
                  echo '<option value="'.$row['id'].'">'.$row['age'].'</option>';
                }
            }else{
                echo '????????????????????????';
            }
            ?>
        </select>
                         </form>  
                         </div>
                         <br/>
                         <br/>
     
    					 <!----------------------------------------->
     
     
     
            <br/>
     
     
    					 <!-------------------------------------------->
                         <table class="table table-bordered">  
                              <tr>  
                                   <th width="5%">Id</th>  
                                   <th width="30%">Name</th>  
                                   <th width="15%">Age</th>  
                                   <th width="50%">Email</th>  
                              </tr>  
                         <?php  
                         echo fetch_data();  
                         ?>  
                         </table>  
                    </div>  
               </div>  
          </body>  
     </html>

    Quelqu'un peut m'aider?

    Merci d'avance.

  2. #2
    Membre chevronné
    Homme Profil pro
    Administrateur de base de données
    Inscrit en
    Avril 2017
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Cameroun

    Informations professionnelles :
    Activité : Administrateur de base de données
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2017
    Messages : 508
    Par défaut
    Bonsoir,
    1) tu veux utiliser une variable que tu n'a pas déclaré.
    2) Tu dis que tu l'as déclaré à la ligne 89.c'est comme ça qu'on déclare une variable en php ?

    Commence par déclarer la variable choix et et restructure ton code en utilisant le MVC.
    Sépare les données des traitements.
    Je constate qu'il y'a mélange de code.

    Cordialement.

  3. #3
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2018
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Septembre 2018
    Messages : 13
    Par défaut
    je suis un débutant dans la programmation.
    comment résoudre ce problème?

  4. #4
    Membre Expert
    Avatar de Dendrite
    Femme Profil pro
    Développeuse informatique
    Inscrit en
    Juin 2008
    Messages
    2 129
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 59
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeuse informatique
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Juin 2008
    Messages : 2 129
    Billets dans le blog
    8
    Par défaut
    Salut. Essaie ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
     
    <?php  
     function fetch_data($choix=NULL)  
     { 
      //Include database configuration file
      //include('dbConfig.php');
      $db = mysqli_connect("localhost", "root", "", "tut");   
      if(! empty ($choix)){
        $ligne_ok = mysqli_query($conn, 'SELECT * FROM pdf_export where age = "'.$choix.'"');
      }
      else{
        $ligne_ok = mysqli_query($conn, 'SELECT * FROM pdf_export');
      }
     
        $output = '';  
    	  while($row = mysqli_fetch_array($ligne_ok))  
          {       
          $output .= '<tr>  
                              <td>'.$row["id"].'</td>  
                              <td>'.$row["name"].'</td>  
                              <td>'.$row["age"].'</td>  
                              <td>'.$row["email"].'</td>  
                         </tr>  
                              ';  
          }  
          return $output;  
     }  
     if(isset($_POST['generate_pdf']) && isset($_POST['choix']) )  
     {  
          require_once('tcpdf/tcpdf.php');  
          $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);  
          $obj_pdf->SetCreator(PDF_CREATOR);  
          $obj_pdf->SetTitle("Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP");  
          $obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);  
          $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));  
          $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));  
          $obj_pdf->SetDefaultMonospacedFont('helvetica');  
          $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);  
          $obj_pdf->SetMargins(PDF_MARGIN_LEFT, '10', PDF_MARGIN_RIGHT);  
          $obj_pdf->setPrintHeader(false);  
          $obj_pdf->setPrintFooter(false);  
          $obj_pdf->SetAutoPageBreak(TRUE, 10);  
          $obj_pdf->SetFont('helvetica', '', 11);  
          $obj_pdf->AddPage();  
          $content = '';  
          $content .= '  
          <h4 align="center">Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP</h4><br /> 
          <table border="1" cellspacing="0" cellpadding="3">  
               <tr>  
                    <th width="5%">Id</th>  
                    <th width="30%">Name</th>  
                    <th width="15%">Age</th>  
                    <th width="50%">Email</th>  
               </tr>  
          ';  
          $content .= fetch_data($_POST['choix']);  
          $content .= '</table>';  
          $obj_pdf->writeHTML($content);  
          $obj_pdf->Output('file.pdf', 'I');  
     }
     
     ?>  
     <!DOCTYPE html>  
     <html>  
          <head>  
               <title>SoftAOX | Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP</title>  
               <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />            
          </head>  
     
     
     
          <body>  
               <br />
               <div class="container">  
                    <h4 align="center"> Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP</h4><br />  
                    <div class="table-responsive">  
                    	<div class="col-md-12" align="right">
                         <form method="post">  
                              <input type="submit" name="generate_pdf" class="btn btn-success" value="Generate PDF" />  
    						  	 <br/>
    <?php
     
     
        //Get all country data
         $query = $db->query("SELECT * FROM  pdf_export ");
     
        //Count total number of rows
        $rowCount = $query->num_rows;
        ?>
     
        <select name="choix" id="choix"  class="form-control" >
            <option value="">Show All</option>
            <?php
            if($rowCount > 0){
     
                while($row = $query->fetch_assoc()){ 
                  echo '<option value="'.$row['id'].'">'.$row['age'].'</option>';
                }
            }else{
                echo '????????????????????????';
            }
            ?>
        </select>
                         </form>  
                         </div>
                         <br/>
                         <br/>
     
    					 <!----------------------------------------->
     
     
     
            <br/>
     
     
    					 <!-------------------------------------------->
                         <table class="table table-bordered">  
                              <tr>  
                                   <th width="5%">Id</th>  
                                   <th width="30%">Name</th>  
                                   <th width="15%">Age</th>  
                                   <th width="50%">Email</th>  
                              </tr>  
                         <?php  
                         echo fetch_data();  
                         ?>  
                         </table>  
                    </div>  
               </div>  
          </body>  
     </html>
    PDO, une soupe et au lit !
    Partir de la fin est un bon moyen de retrouver son chemin. Bibi - 2020

  5. #5
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2018
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Septembre 2018
    Messages : 13
    Par défaut
    j'ai essai mais affiche un message:

    Fatal error: Uncaught ArgumentCountError: Too few arguments to function fetch_data(), 0 passed in C:\xampp\htdocs\pdf_export\index.php on line 126 and exactly 1 expected in C:\xampp\htdocs\pdf_export\index.php:6 Stack trace: #0 C:\xampp\htdocs\pdf_export\index.php(126): fetch_data() #1 {main} thrown in C:\xampp\htdocs\pdf_export\index.php on line 6
    je pense la fonction fetch_data() est vide, porquoi affiche ce message.

  6. #6
    Invité
    Invité(e)
    Par défaut
    Bonjour,

    1- si tu veux progresser, il faut d'abord comprendre les messages d'erreur :

    Fatal error: Uncaught ArgumentCountError: Too few arguments to function fetch_data(),
    0 passed in C:\xampp\htdocs\pdf_export\index.php on line 126
    and exactly 1 expected
    in C:\xampp\htdocs\pdf_export\index.php:6
    Stack trace: #0 C:\xampp\htdocs\pdf_export\index.php(126): fetch_data() #1 {main} thrown in C:\xampp\htdocs\pdf_export\index.php on line 6
    1. Too few arguments to function fetch_data() : "pas assez de paramètres passés à la fonction fetch_data()"
    2. index.php on line 126 : fichier index.php, à la ligne 126
    3. ...


    2- Le premier réflexe est donc de REGARDER à la ligne 126 !

    On trouve ligne 126 :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    <?php
                         echo fetch_data();
    Or, la fonction a été déclarée avec un paramètre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     function fetch_data($choix=NULL)
    CORRECTION : On doit écrire ligne 126 :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    <?php
                         $choix = ( isset($_POST['choix']) )? $_POST['choix'] : '';
                         echo fetch_data( $choix );
    3- IMPORTANT : il faut SECURISER la REQUETE SQL avec mysqli_real_escape_string() :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     function fetch_data($choix=NULL)  
     { 
    ..........
      if(! empty ($choix)){
        $ligne_ok = mysqli_query($conn, 'SELECT * FROM pdf_export where age = "'.mysqli_real_escape_string($choix).'"');
    ..........

  7. #7
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2018
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Septembre 2018
    Messages : 13
    Par défaut
    je fais tout que vous dites,

    quand je exécute le code affiche tous les information dans un tableau, mais quand je chois un champ de ma liste déroulante cela ne change rien sur ce tableau par rapport a ce choix, ainsi que je clique sur le bouton " Generate PDF " affiche ce message:

    Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\pdf_export\index.php on line 9 ;
    voilà la ligne 9:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    $ligne_ok = mysqli_query($conn, 'SELECT * FROM pdf_export where age =\''.mysqli_real_escape_string($choix).'\'');
    j'ai ajouter un morceau de code modification:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    if(isset($_POST['choix'] ))
    {
    	if(!empty($_POST['choix']))
    	{
    		  echo "est rempli";
    	}
    	else
    	{
    		echo "est vide";
    	}
    }
    else
    {
    	echo "variable n'existe pas";
    }
    un message est affiché : variable n'existe pas.

  8. #8
    Invité
    Invité(e)
    Par défaut
    OK. Mea culpa

    Je t'ai mis un lien. AS-TU LU LA DOCUMENTATION de mysqli_real_escape_string() ??

    Il manque le paramètre de connexion (Style procédural) :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    mysqli_real_escape_string($conn, $choix)
    Ça, tu dois être capable de le trouver tout seul, non ?

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 0
    Dernier message: 05/06/2010, 00h08
  2. [AC-2000] Récupérer la valeur d’une liste déroulante pour filtrer une requête SQL
    Par Gremandine dans le forum Requêtes et SQL.
    Réponses: 6
    Dernier message: 18/03/2010, 15h43
  3. Récupérer une valeur de liste modifiable pour
    Par adriennoob dans le forum IHM
    Réponses: 3
    Dernier message: 17/07/2009, 08h12
  4. Réponses: 3
    Dernier message: 15/06/2007, 12h06
  5. Réponses: 11
    Dernier message: 29/05/2007, 08h05

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo