Skip to content Skip to sidebar Skip to footer

Creating A Crud Using Php + Bootstrap Modal + Mysql + Js

I need a page with a button to insert a new user, with fields 'country','name' and 'company'. Then, in the same page, I need to list those datas and in front each item it'll appear

Solution 1:

I see what you have now. Thanks for adding the code. I would first focus on design. It sounds like you want some sort of CRUD(Create Retrieve Update Delete) system. In that case, what I would do, is place the initial submission form on top (like what you have), and use modals to show any alert messages and the Edit form.

The design would look like this:

+-------------------------------------+| Submit Form                         ||- input                             ||- input                             |+-------------------------------------+| List showing DB info                ||-result1 (with Edit/Delete links) ||-result2 (with Edit/Delete links) || ...                                 |+-------------------------------------+

At page load, you will run an JS function, we can call it update_list(), that will use AJAX to fetch all the database info and parse it in the List container.

Then you will delegate Edit/Delete Click events to call the desired AJAX calls.

Keep in mind, this design structure separates everything in functions and uses AJAX to call on PHP scripts. The data will be sent via JSON.

Now, when you Submit the submission form, this will also use AJAX to send POST requests to PHP, then once submitted, JS will use Bootstrap's modal to show messages.

When the edit link is clicked, JS will again open a Bootstrap modal to show the edit form.

With that said, this is how I would do it :

<html><title>Modal</title><metahttp-equiv="Content-Type"content="text/html; charset=iso-8859-1"><head><linkrel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><scriptsrc="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script><style>#wrapper {
                padding: 10px;
            }

            .modal-header, h4, .close {
                background-color: #5cb85c;
                color: white !important;
                text-align: center;
                font-size: 30px;
            }

            .modal-footer {
                background-color: #f9f9f9;
            }
        </style></head><body><divid="wrapper"><formid="submit_form"role="form"style="width: 300px;"><divclass="form-group"><labelfor="pais">Pais:</label><?php$array_pais = array('Selecione...', 'Alemanha', 'Angola', 'Argentina', 'Bolívia', 'Brasil', 'Camarões', 'Canadá', 'Chile', 'China', 'Colombia',
                        'Costa Rica', 'Cuba', 'Dinamarca', 'Equador', 'Espanha', 'Estados Unidos', 'França', 'Holanda', 'Inglaterra', 'Itália', 'Japão',
                        'México', 'Nigéria', 'Panamá', 'Paraguai', 'Peru', 'Porto Rico', 'Portugal', 'Rússia', 'Senegal', 'Taiwan', 'Uruguai', 'Venezuela'
                    );
                    echo'<select class="form-control" name="pais" id="pais">';
                    foreach ($array_paisas$valor) {
                        echo'<option>' . $valor . '</option>';
                    }
                    echo'</select>';
                    ?></div><divclass="form-group"><labelfor="nome">Nome:</label><inputclass="form-control"name="nome"type="text"id="nome"size="50"></div><divclass="form-group"><labelfor="empresa">Empresa:</label><inputclass="form-control"name="empresa"type="text"id="empresa"size="50"style="text-transform:uppercase;"></div><inputtype="submit"name="Submit"class="btn btn-success btn-lg"value="+"></form><tableid="list"class="table"><theadalign="center"><trbgcolor="#B0E2FF"><th>PAÍS</th><th>NOME</th><th>EMPRESA</th><th>AÇÕES</th></tr></thead><tbody></tbody></table><divclass="modals_container"><divclass="modal fade"id="message_modal"role="dialog"><divclass="modal-dialog"><divclass="modal-content"><divclass="modal-header"><buttontype="button"class="close"data-dismiss="modal">&times;</button><h4class="modal-title">Message</h4></div><divclass="modal-body"></div><divclass="modal-footer"><buttontype="button"class="btn btn-default"data-dismiss="modal">Close</button></div></div></div></div><divclass="modal fade"id="edit_modal"role="dialog"><divclass="modal-dialog"><formid="edit_form"class="form"><divclass="modal-content"><divclass="modal-header"><buttontype="button"class="close"data-dismiss="modal">&times;</button><h4class="modal-title">Edit</h4></div><divclass="modal-body"><divclass="form-group">
                                        Country: <inputid="country_input"type="text"name="country"></div><divclass="form-group">
                                        Nome: <inputid="username_input"type="text"name="username"></div><divclass="form-group">
                                        Company: <inputid="company_input"type="text"name="company"></div><inputid="id_input"type="hidden"name="id"></div><divclass="modal-footer"><buttontype="button"class="btn btn-default"data-dismiss="modal">Cancel</button><buttontype="submit"class="btn btn-default">submit</button></div></div></form></div></div></div></div><script>functionupdate_list() {
                $.getJSON("get_list.php", function (data) {

                    if (data.response) {
                        $("#list").find("tbody").empty();
                        data.results.forEach(function (i) {
                            console.log(i);
                            $("#list").find("tbody").append(
                                "<tr>" +
                                "<td>" + i.country + "</td>" +
                                "<td>" + i.username + "</td>" +
                                "<td>" + i.company + "</td>" +
                                "<td><a class='edit_link' href='" + JSON.stringify(i) + "'>edit</a> | <a class='delete_link' href='" + i.id + "'>delete</a></td>" +
                                "</tr>"
                            );
                        });
                    }

                });
            }
            update_list();
            $('#submit_form').submit(function () {
                $.ajax({
                    url: "main.php",
                    type: "POST",
                    data: $(this).serialize(),
                    dataType: "json",
                    success: function (data) {
                        if (data.response) {
                            var $modal = $('#message_modal');
                            $modal.find(".modal-body").html(data.message);
                            $modal.modal('show');
                            update_list();
                        } else {
                            alert(data.message);
                        }
                    }
                });
                returnfalse;
            });

            $("#list").delegate('.edit_link', 'click', function (e) {
                e.preventDefault();
                var info = JSON.parse($(this).attr("href"));
                var $modal = $("#edit_modal");
                $modal.find("#country_input").val(info.country);
                $modal.find("#company_input").val(info.company);
                $modal.find("#username_input").val(info.username);
                $modal.find("#id_input").val(info.id);
                $modal.modal('show');
            });

            $('#edit_form').submit(function () {
                $.ajax({
                    url: "edit.php",
                    type: "POST",
                    data: $(this).serialize(),
                    dataType: "json",
                    success: function (data) {
                        if (data.response) {
                            var $modal = $('#message_modal');
                            $("#edit_modal").modal('hide');
                            $modal.find(".modal-body").html(data.message);
                            $modal.modal('show');
                            update_list();
                        } else {
                            alert(data.message);
                        }
                    }
                });
                returnfalse;
            });
        </script></body></html>

edit.php should be something like this:

$con = mysqli_connect("localhost", "root", "", "test");

// Check connectionif (mysqli_connect_errno()) {
    echo"Failed to connect to MySQL: " . mysqli_connect_error();
}

$id = $_POST['id'];
$nome = $_POST['username'];
$company = $_POST['company'];
$country = $_POST['country'];


$query = "UPDATE table SET username = '$nome', company = '$company', country= '$country' WHERE id = $id ";

if (mysqli_query($con, $query)) {
    $res['response'] = true;
    $res['message'] = "Record has been updated";
} else {
    $res['response'] = false;
    $res['message'] = "Error: " . $query . "<br>" . mysqli_error($con);
}

echo json_encode($res);

Try this out, and let me know what you think.

Solution 2:

I've not changed much php code of yours. I added little code to it. In , i added code to call editar.php modal. In that script tag.. more code were there.. I don't know what is that.

index.php

//
Your original code here(No changes). From down, it started changing
//
<tabledata-toggle="table"data-cache="false"><theadalign="center"><trheight="35px"valign="center"bgcolor="#B0E2FF" ><thstyle="text-align:center; vertical-align:middle; width="100px">PAÍS</th><thstyle="text-align:center; vertical-align:middle; width="250px">NOME</th><thstyle="text-align:center; vertical-align:middle; width="300px">EMPRESA</th><thstyle="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th></tr></thead><?while($result = mysql_fetch_array($limite)){ ?><tbody><tr><tdstyle="display:none"align="center"><?=$result['id']; $_SESSION=$result['id'];?></td><tdstyle="vertical-align:middle;"><?=$result['pais']?></td><tdstyle="vertical-align:middle;"><?=$result['nome']?></td><tdstyle="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td><tdstyle="width:20px">

            //Some Changes Here.. check it

            <aclass='btnEdit'href="#form_modal"data-toggle="modal"data-EditID="<?echo$result['id'];?>"><spanclass='glyphicon glyphicon-pencil'></span><a></td><tdstyle="width:20px"><aclass="btn btn-danger glyphicon glyphicon-trash"title="Deletar"href="deletar.php?id=<?=$result['id'];?>"></a></td></tr></tbody><?}?></table>

//Add this code.
<divid="form_modal"class="modal fade"aria-hidden="true"><divclass="modal-dialog"><divclass="modal-content"></div></div></div>

//Added few codes in script for calling modal.
<script>
    $('form').submit(function () {
       var postdata = {
           pais: $(this)[0].pais.value,
           nome: $(this)[0].nome.value,
           empresa: $(this)[0].empresa.value 
        }
        $.post("inserir.php", postdata, function (d) {
        $('#myModal').find(".modal-body").html(d);
        $('#myModal').modal('show');
        });
        returnfalse;
    });
    $('.btnEdit').click(function(){
        var id=$(this).attr('data-EditID');
        $.ajax({url:"editar.php?id="+id,cache:false,success:function(result){
            $(".modal-content").html(result);
        }});
    });
</script>

Make One editar.php. Paste this below code in that page. editar.php

<divclass="modal-header"><buttontype="button"class="close"data-dismiss="modal"aria-hidden="true"></button><h4class="modal-title"><spanclass="glyphicon glyphicon-pencil"></span> Novo registro
    </h4></div><divclass="modal-body"style='text-align:justify;'><?echo$_GET['id'];?>   
    //Show Details Here.    
</div><divclass="modal-footer"><buttontype="submit"class="btn btn-primary">Submit</button><buttontype="button"class="btn btn-default"data-dismiss="modal">Fechar</button></div>

Post a Comment for "Creating A Crud Using Php + Bootstrap Modal + Mysql + Js"