How to send data from a modal bootstrap dialog to a table in mysql?

2

I have a table in mysql called jobs that has three fields (Job_id, Job_Name and Cost) which has data and I show them in this table in html

Now what I want is that when selecting edit, I can modify the name and the cost and that this change is also saved directly in the database, by clicking on edit I have a modal-dialog like this:

but clicking on update does not do anything to me, this is my code

<form name="form2" method="post" action="actualizar_lista.php">
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
        
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
              <h4 class="modal-title custom_align" id="Heading">Editar informacion</h4>
            </div>
          
            <div class="modal-body">

                 <div class="form-group">
                <input class="form-control " type="text" placeholder="id" id="txt_id">
              </div>
            
              <div class="form-group">
                <input class="form-control " type="text" placeholder="Nombre del trabajo" id="txt_nombre">
              </div>

              <div class="form-group">
                <input class="form-control " type="text" placeholder="Costo" id="txt_costo">
              </div>
            
          
            <div class="modal-footer ">
              <button type="button" class="btn btn-warning btn-lg">Actualizar</button>
            </div>
        </div>
      </div>
  </div>
</div>
</form>

and this is my php code for the query

 <!--LIBRERIAS DE ESTILOS DE BOOTSTRAP-->
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minium-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.min.css"> 
    <link rel="stylesheet" href="css/bootstrap.css">
     <link rel="stylesheet" href="consulta_lista.js">

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
        <script src="js/jquery-3.1.0.js"></script>

<?

  $conexion= mysqli_connect("localhost", "root", "root", "registros");
  if($conexion)
    {
    
      //Variables
      $Id_Trabajo=$_POST['txt_id'];
      $Nombre_Trabajo = $_POST['txt_nombre'];
      $Costo=$_POST['txt_costo'];

     
      //realiza la consulta
      $consulta= "UPDATE trabajos set Nombre_Trabajo='$Nombre_Trabajo'and Costo='$Costo' WHERE Id_trabajo='$Id_Trabajo'";
  
  

      //para ejecutar consulta
      $resultado=mysqli_query($conexion ,$consulta);
 
        if ($resultado) 
          {   ?>

          <div class="alert alert-success">
            <strong>Datos guardados correctamente!</strong> 
            <a href="ingresar.html" class="alert-link">Volver</a>
          </div>
        <?}
    
        else { ?>
          <div class="alert alert-warning">
            <strong>Error al guardar los datos!</strong>
            <a href="ingresar.html" class="alert-link">Volver</a>
          </div>
         <?php } 
      
      }else{ 
        echo ""; 
        }
    
        mysqli_close($conexion);   
      ?> 
    
asked by Root93 05.10.2016 в 19:32
source

5 answers

2

1.- Use the JQuery click event to receive the event, within the event retrieve the content of the field and validate the data if you require it.

link

2.- Once the above is done, you can send it through ajax de jquery and send it to a page where you can connect to your DB

$.ajax({
  method: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });
    
answered by 05.10.2016 в 19:40
0
    <form name="form2" method="POST" action="actualizar_lista.php">
  <div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">

        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
          <h4 class="modal-title custom_align" id="Heading">Editar informacion</h4>
        </div>

        <div class="modal-body">

             <div class="form-group">
            <input class="form-control " type="text" placeholder="id" id="txt_id" name="txt_id">
          </div>

          <div class="form-group">
            <input class="form-control " type="text" placeholder="Nombre del trabajo" id="txt_nombre" name="txt_nombre">
          </div>

          <div class="form-group">
            <input class="form-control " type="text" placeholder="Costo" id="txt_costo" name="txt_costo">
          </div>


      <div class="form-group" align="center">

     <input type="submit"  class="btn btn-warning" name="btn"  id="btn" value="Actualizar"/>

    </div>
    </div>
    </div>
    </div>
    </div>
    </form>


    Archivo Actualizar_lista.php

          include("conexion.php");
          $txt_id=$_POST["txt_id"];
          $txt_nombre=$_POST["txt_nombre"];
          $txt_costo=$_POST["txt_costo"];
    $sql=mysqli_query($conexion,"update nombretabla set nombre=$txt_nombre, costo=$txt_costo where id=$txt_id");
    if ($conexion->query($sql) === TRUE) {
    echo "Actualizado Correctamente";
     }
    
answered by 05.10.2016 в 20:03
0

Try not to concatenate the data entered by the user into the query, otherwise you will be vulnerable to SQLi Also, your code can be better organized if you do not mix views with backend. You can see more about separation of interests here .

edit.php

// variables
$data = json_decode($_POST['data']);
$id_trabajo = $data[0]['id_trabajo'];
$nombre_trabajo = $data[1]['nombre_trabajo'];
$costo = $data[2]['costo'];

// realiza la consulta
$query = "UPDATE trabajos SET nombre_trabajo=?, costo=? WHERE id_trabajo=?";
$pstmt = $conn->prepare($query);
$pstmt->bind_param("sdi", $id_trabajo, $nombre_trabajo, $costo);

if($pstmt->execute($pstmt)) {
  json_encode(array("status" => "OK"));
} else {
  json_encode(array(
    "status" => "FAIL",
    "error" => $conn->error
  ));
}

modal

For semantic reasons it is better to use forms even if you use AJAX. This helps to quickly identify which group of data will be sent to the server.

<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
  <div class="modal-dialog modal-sm" role="document">
    <form class="modal-content" action="actualizar_trabajo.php" method="POST">
      <div class="modal-header">
        <button type="button" class="close" 
                data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title">Editar trabajo</h4>
      </div>
      <div class="modal-body">
          <div class="form-group">
            <input class="form-control " type="hidden" placeholder="id" name="txt_id">
          </div>
          <div class="form-group">
            <input class="form-control " type="text" placeholder="Nombre del trabajo" name="txt_nombre">
          </div>
          <div class="form-group">
            <input class="form-control " type="text" placeholder="Costo" name="txt_costo">
          </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
        <button type="submit" class="btn btn-primary">Guardar</button>
      </div>
    </form>
  </div>
</div>

JavaScript

$('.modal form').on('submit', function(e) {
  e.preventDefault();
  $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: { data: $(this).serializeArray() }
  })
  .done(function(response) {
    if(response.status === "OK") {
      $('.modal').modal('hide');
    } else {
      // mostrar el error al usuario
    }
  });
});
    
answered by 05.10.2016 в 23:55
0

It is considered necessary to add the name attribute for each of the form's fields, so that the values can be taken through the array $ _POST ['field_name']:

<input class="form-control " type="text" placeholder="id" id="txt_id" name="txt_id">
    
answered by 06.10.2016 в 05:41
0

If it were my case, I would use ajax.

  • I would put a div inside the modal window that contains only the form with the button.
  • I would get the value (id that I want to edit) with the edit button. With my ajax I would send it to a separate file that would contain all the structure html but watch out! it must be inside the php, where it would perform the query and it would bring the data of that id. I print my structure html with your data in the - "value" with an "echo".
  • Once this is done, you will be able to see your modal window with the data of the selected id.
  • In your PHP containing the update you only receive the data. and update.
  • Sorry for not appending example. But I attach a page that helped me in time to do something similar to your question link

        
    answered by 05.10.2016 в 22:42