Bonjour,

J'ai besoin de votre aide concernant un CRUD Ajax trouvé sur le net qui semblait très simple.
Mon problème est que je n'arrive pas à insérer les valeurs du formulaire dans ma bdd (mysql), alors que le select l'affiche correctement, que le update fonctionne et le delete également.

Je sais que le problème est tout bête mais je n'arrive pas à l’apercevoir

Pouvez vous m'aider please ?
Je vous remercie d'avance.

Index.php

Code html : 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
<html>
 <head>
  <title>Catalogue - Liste des Articles</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script>
  $(document).ready(function(){
   fetchUser(); //This function will load all data on web page when page load
   function fetchUser() // This function will fetch data from table and display under <div id="result">
   {
    var action = "Load";
    $.ajax({
     url : "action.php",
     method:"POST",
     data:{action:action}, //action variable data has been send to server
     success:function(data){
      $('#result').html(data); //It will display data under div tag with id result
     }
    });
   }
 
   //This JQuery code will Reset value of Modal item when modal will load for create new records
   $('#modal_button').click(function(){
    $('#articleform').modal('show'); //It will load modal on web page
    $('#categorie').val('');
    $('#nom').val('');
        $('#prix').val('');
        $('#detail').val('');
        $('#image').val('');
    $('.modal-title').text("Creer un nouvel Article"); //It will change Modal title to Nouvel Article
    $('#action').val('Creer'); //This will reset Button value ou Creer
   });
 
   //This JQuery code is for Click on Modal action button for Create new records or Update existing records. This code will use for both Create and Update of data through modal
   $('#action').click(function(){
    var categorie = $('#categorie').val(); //Get the value of first name textbox.
        var nom = $('#nom').val(); //Get the value of first name textbox.
        var prix = $('#prix').val(); //Get the value of first name textbox.
    var detail = $('#detail').val(); //Get the value of last name textbox
        var image = $('#image').val(); //Get the value of last name textbox
    var id = $('#id').val();  //Get the value of hidden field customer id
    var action = $('#action').val();  //Get the value of Modal Action button and stored into action variable
    if(categorie != '' && nom != '') //This condition will check both variable has some value
    {
     $.ajax({
      url : "action.php",    //Request send to "action.php page"
      method:"POST",     //Using of Post method for send data
      data:{categorie:categorie, nom:nom, id:id, prix:prix, detail:detail, image:image, action:action}, //Send data to server
      success:function(data){
       alert("data");    //It will pop up which data it was received from server side
       $('#articleform').modal('hide'); //It will hide Customer Modal from webpage.
       fetchUser();    // Fetch User function has been called and it will load data under divison tag with id result
      }
     });
    }
    else
    {
     alert("Les champs sont obligatoires"); //If both or any one of the variable has no value them it will display this message
    }
   });
 
   //This JQuery code is for Update customer data. If we have click on any customer row update button then this code will execute
   $(document).on('click', '.update', function(){
    var id = $(this).attr("id"); //This code will fetch any article id from attribute id with help of attr() JQuery method
    var action = "Select";   //We have define action variable value is equal to select
    $.ajax({
     url:"action.php",   //Request send to "action.php page"
     method:"POST",    //Using of Post method for send data
     data:{id:id, action:action},//Send data to server
     dataType:"json",   //Here we have define json data type, so server will send data in json format.
     success:function(data){
      $('#articleform').modal('show');   //It will display modal on webpage
      $('.modal-title').text("Modifier un article"); //This code will change this class text to Update records
      $('#action').val("Update");     //This code will change Button value to Update
      $('#id').val(id);     //It will define value of id variable to this customer id hidden field
      $('#categorie').val(data.categorie);  //It will assign value to modal first name texbox
      $('#nom').val(data.nom);    //It will assign value of modal last name textbox
          $('#prix').val(data.prix);
          $('#detail').val(data.detail);
          $('#image').val(data.image);
     }
    });
   });
 
   //This JQuery code is for Delete customer data. If we have click on any customer row delete button then this code will execute
   $(document).on('click', '.delete', function(){
    var id = $(this).attr("id"); //This code will fetch any customer id from attribute id with help of attr() JQuery method
    if(confirm("Voulez vous vraiment supprimer cet article?")) //Confim Box if OK then
    {
     var action = "Delete"; //Define action variable value Delete
     $.ajax({
      url:"action.php",    //Request send to "action.php page"
      method:"POST",     //Using of Post method for send data
      data:{id:id, action:action}, //Data send to server from ajax method
      success:function(data)
      {
       fetchUser();    // fetchUser() function has been called and it will load data under divison tag with id result
       alert(data);    //It will pop up which data it was received from server side
      }
     })
    }
    else  //Confim Box if cancel then
    {
     return false; //No action will perform
    }
   });
  });
  </script>
 
 </head>
 <body>
  <div class="container">
   <h1 align="center">Catalogue - Gestion des Articles</h1>
   <br />
   <div align="right">
    <button type="button" id="modal_button" class="btn btn-info">Creer</button>
    <!-- It will show Modal for Create new Records !-->
   </div>
   <br />
   <div id="result" class="table-responsive"> <!-- Data will load under this tag!-->
 
   </div>
  </div>
  <!-- This is Customer Modal. It will be use for Create new Records and Update Existing Records!-->
  <div id="articleform" class="modal fade">
   <div class="modal-dialog">
    <div class="modal-content">
     <div class="modal-header">
      <h4 class="modal-title">Creer nouvel article</h4>
     </div>
     <div class="modal-body">
      <label>Categorie</label>
      <input type="text" name="categorie" id="categorie" class="form-control"  pattern="[A-Za-z]{1,25}" />
      <br />
      <label>Nom</label>
      <input type="text" name="nom" id="nom" class="form-control"  pattern="[A-Za-z]{1,25}"/>
      <br />
	  <label>Prix</label>
      <input type="text" name="prix" id="prix" class="form-control"  pattern="[A-Za-z]{1,25}"/>
      <br />
	  <label>Detail</label>
      <input type="text" name="detail" id="detail" class="form-control"  pattern="[A-Za-z]{1,25}"/>
      <br />
	  <label>Image</label>
      <input type="text" name="image" id="image" class="form-control"  pattern="[A-Za-z]{1,25}"/>
      <br />
     </div>
     <div class="modal-footer">
      <input type="hidden" name="id" id="id" />
      <input type="submit" name="action" id="action" class="btn btn-success" />
      <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
     </div>
    </div>
   </div>
  </div>
 
 </body>
</html>

action.php
Code php : 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
132
133
134
135
136
137
138
139
140
141
142
143
144
<?php
//Database connection by using PHP PDO
$username = 'username';
$password = 'password';
$connection = new PDO( 'mysql:host=;dbname=beepbeep74', $username, $password ); // Create Object of PDO class by connecting to Mysql database
if(isset($_POST["action"])) //Check value of $_POST["action"] variable value is set to not
{
 //For Load All Data
 if($_POST["action"] == "Load")
 {
  $statement = $connection->prepare("SELECT * FROM produit ORDER BY id DESC");
  $statement->execute();
  $result = $statement->fetchAll();
  $output = '';
  $output .= '
  <div class="table-responsive">
   <table class="table table-bordered table-hover">
    <tr>
     <th width="20%">Categorie</th>
     <th width="20%">Nom</th>
	 <th width="20%">Prix</th>
	 <th width="20%">Detail</th>
	 <th width="20%">Image</th>
     <th width="10%">Update</th>
     <th width="10%">Delete</th>
    </tr>
  ';
  if($statement->rowCount() > 0)
  {
   foreach($result as $row)
   {
    $output .= '
    <tr>
     <td>'.$row["categorie"].'</td>
     <td>'.$row["nom"].'</td>
	 <td>'.$row["prix"].'</td>
	 <td>'.$row["detail"].'</td>
	 <td>'.$row["image"].'</td>
     <td><center><button type="button" id="'.$row["id"].'" class="btn btn-warning update">Update</button></center></td>
     <td><center><button type="button" id="'.$row["id"].'" class="btn btn-danger delete">Delete</button></center></td>
    </tr>
    ';
   }
  }
  else
  {
   $output .= '
    <tr>
     <td align="center">Erreur !</td>
    </tr>
   ';
  }
  $output .= '</table></div>';
  echo $output;
 }
 
 //This code for Create new Records
 if($_POST["action"] == "Create")
 {
  $statement = $connection->prepare("
   INSERT INTO produit (categorie, nom, prix, detail, image)
   VALUES (:categorie, :nom, :prix, :detail, :image)
  ");
  $result = $statement->execute(
   array(
    ':categorie' => $_POST["categorie"],
    ':nom' => $_POST["nom"],
	':prix' => $_POST["prix"],
	':detail' => $_POST["detail"],
	':image' => $_POST["image"]
   )
  );
  if(!empty($result))
  {
   echo 'Article ajoute avec succes';
  }
 }
 
 //This Code is for fetch single customer data for display on Modal
 if($_POST["action"] == "Select")
 {
  $output = array();
  $statement = $connection->prepare(
   "SELECT * FROM produit
   WHERE id = '".$_POST["id"]."'
   LIMIT 1"
  );
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $output["categorie"] = $row["categorie"];
   $output["nom"] = $row["nom"];
   $output["prix"] = $row["prix"];
   $output["detail"] = $row["detail"];
   $output["image"] = $row["image"];
  }
  echo json_encode($output);
 }
 
 if($_POST["action"] == "Update")
 {
  $statement = $connection->prepare(
   "UPDATE produit
   SET categorie = :categorie, nom = :nom, prix = :prix, detail = :detail, image = :image
   WHERE id = :id
   "
  );
  $result = $statement->execute(
   array(
    ':categorie' => $_POST["categorie"],
    ':nom' => $_POST["nom"],
    ':prix' => $_POST["prix"],
	':detail' => $_POST["detail"],
	':image' => $_POST["image"],
	':id'   => $_POST["id"]
 
   )
  );
  if(!empty($result))
  {
   echo 'Article mis a jour';
  }
 }
 
 if($_POST["action"] == "Delete")
 {
  $statement = $connection->prepare(
   "DELETE FROM produit WHERE id = :id"
  );
  $result = $statement->execute(
   array(
    ':id' => $_POST["id"]
   )
  );
  if(!empty($result))
  {
   echo 'Article supprime';
  }
 }
 
}
 
?>