Creating a CRUD using PHP + Bootstrap Modal + Mysql + JS [closed]

陌路散爱 提交于 2019-12-13 09:46:10

问题


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 two buttons, "edit" and "delete". At edit button, I need to display a Modal window (bootstrap), so I could update this data. I hope someone could help me. Thanks

Sorry, I've forgot to paste the code.

This is my index.php:

    <form action="inserir.php" method="post" name="visitas" id="visitas">
            <table class="table_geral" align="center" width="350" border="0" cellspacing="0" cellpadding="3">  
                <tr>
                    <td width="200">Pais:</td>
                    <td>
                        <?
                        $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" style="width:330px" name="pais" id="pais">';
                        foreach($array_pais as $valor){
                            echo '<option>'.$valor.'</option>';
                        }
                        echo '</select>'; 
                        ?>
                    </td>
                    <td height="29" valign="center" align="center" rowspan="3">&nbsp </td>
                    <td height="29" valign="center" align="center" rowspan="3">
                        <input type="submit" name="Submit" class="btn btn-success btn-lg" value=" + ">
                    </td>
                </tr>
                <tr>
                    <td width="411">Nome:</td>
                    <td width="339">
                        <input class="form-control" name="nome" type="text" id="nome" size="50">
                    </td>
                </tr>
                <tr>
                    <td width="411">Empresa:</td>
                    <td width="339">
                        <input class="form-control" name="empresa" type="text" id="empresa" size="50" style="text-transform:uppercase;">
                    </td>
                </tr>
            </table>
        </form>


    $sql = "SELECT * FROM tb_visitas ORDER BY empresa";
    $limite = mysql_query("$sql"); ?>       

 <table data-toggle="table" data-cache="false">
                    <thead align="center">
                        <tr height="35px" valign="center" bgcolor="#B0E2FF" >
                            <th style="text-align:center; vertical-align:middle; width="100px">PAÍS</th>
                            <th style="text-align:center; vertical-align:middle; width="250px">NOME</th>
                            <th style="text-align:center; vertical-align:middle; width="300px">EMPRESA</th>
                            <th style="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th>
                        </tr>
                    </thead>
                    <? while($result = mysql_fetch_array($limite)){ ?>
                    <tbody>
                        <tr>
                            <td style="display:none" align="center"><?=$result['id']; $_SESSION=$result['id'];?></td>
                            <td style="vertical-align:middle;"> <?=$result['pais']?></td>
                            <td style="vertical-align:middle;"> <?=$result['nome']?></td>
                            <td style="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td>
                            <td style="width:20px">
                            <form action="editar.php" method="post">
                                <a class="btn btn-primary glyphicon glyphicon-pencil" title="Editar" href="editar.php?id=<?=$result['id'];?>"></a>
                            </form>
                            </td>
                            <td style="width:20px">
                                <a class="btn btn-danger glyphicon glyphicon-trash" title="Deletar" href="deletar.php?id=<?=$result['id'];?>"></a>
                            </td>
                        </tr>
                    </tbody>
                    <?}?>
                </table>

<div class="container">
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">
                    <span class="glyphicon glyphicon-pencil"></span> Novo registro</h4>
                </div>
                <div class="modal-body">
                    <p></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                </div>
            </div>
        </div>
    </div>
</div>

    <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');
            });
            return false;
        });
    </script>

And it's my inserir.php:

<?
require("conexao.php");

    $pais = $_POST['pais'];
    $nome = $_POST['nome'];
    $empresa = $_POST['empresa'];

    if (($pais == "") || ($pais == "Selecione...") || ($nome == "") || ($empresa == "")) { 
        echo "Favor preencha todos os campos!";
    } else {
        $sql = mysql_query("SELECT nome FROM tb_visitas WHERE nome='$nome'");

        if (mysql_num_rows($sql) > 0) { 
            echo "O nome <b>$nome</b> ja foi inserido na lista!";
        } else {
            $sqlinsert = "INSERT INTO tb_visitas VALUES (null, '$pais', '$nome', UPPER('$empresa'))";
            mysql_query($sqlinsert) or die (mysql_error());
            echo "Gravado com sucesso!";
        }
    }       

?>

With assist from CodeGodie now I have this code, but I need to open a Modal window (bootstrap) to edit some register. However I don't know how to make it with AJAX. I feel sorry for my bad explanation and my English. Thanks


Sorry, but I'm beginner in php and ajax. There are much code that I've never seen :( ....Then, I'm having some difficulty to make it work out. I thought it was simplest. However I tried to make the files:

editar.php

$con = mysql_connect("localhost", "root", "", "visitas");

// Check connection
if (mysql_error()) {
    echo "Failed to connect to MySQL: " . mysql_error();
}

$id = $_POST['id'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$pais = $_POST['pais'];


$query = "UPDATE tb_visitas SET nome = '$nome', empresa = '$empresa', pais= '$pais' WHERE id = $id ";

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

echo json_encode($res);

deletar.php

<?php

require("conexao.php");

$id = $_POST['id'];

if  (isset($_POST['id'])) {
    $sql = "DELETE FROM tb_visitas WHERE id = $id";
    $deletar = mysql_query($sql) or die (mysql_error());        
}

?> 

get_list.php

$con = mysql_connect("localhost", "root", "", "visitas");

if (mysql_error()) {
    echo "Failed to connect to MySQL: " . mysql_error();
}

$id = $_POST['id'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$pais = $_POST['pais'];

$query  = "SELECT * FROM tb_visitas";


?>

conexão.php

<?

error_reporting(E_ALL ^ E_DEPRECATED);

$hostname = 'localhost';
$username = 'root';
$senha = '';
$banco = 'visitas';

$db = mysql_connect($hostname, $username, $senha); 
mysql_set_charset('latin1',$db);
mysql_select_db($banco, $db) or die ("Não foi possível conectar ao banco MySQL");

?>

回答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                |
| - result 1 (with Edit/Delete links) |
| - result 2 (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>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <head>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="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>
        <div id="wrapper">
            <form id="submit_form" role="form" style="width: 300px;">
                <div class="form-group">
                    <label for="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_pais as $valor) {
                        echo '<option>' . $valor . '</option>';
                    }
                    echo '</select>';
                    ?>
                </div>
                <div class="form-group">
                    <label for="nome">Nome:</label>
                    <input class="form-control" name="nome" type="text" id="nome" size="50">
                </div>
                <div class="form-group">
                    <label for="empresa">Empresa:</label>
                    <input class="form-control" name="empresa" type="text" id="empresa" size="50" style="text-transform:uppercase;">
                </div>
                <input type="submit" name="Submit" class="btn btn-success btn-lg" value="+">
            </form>


            <table id="list" class="table">
                <thead align="center">
                    <tr bgcolor="#B0E2FF">
                        <th>PAÍS</th>
                        <th>NOME</th>
                        <th>EMPRESA</th>
                        <th>AÇÕES</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>

            <div class="modals_container">
                <div class="modal fade" id="message_modal" role="dialog">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <h4 class="modal-title">Message</h4>
                            </div>
                            <div class="modal-body"></div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal fade" id="edit_modal" role="dialog">
                    <div class="modal-dialog">
                        <form id="edit_form" class="form">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    <h4 class="modal-title">Edit</h4>
                                </div>
                                <div class="modal-body">
                                    <div class="form-group">
                                        Country: <input id="country_input" type="text" name="country">
                                    </div>
                                    <div class="form-group">
                                        Nome: <input id="username_input" type="text" name="username">
                                    </div>
                                    <div class="form-group">
                                        Company: <input id="company_input" type="text" name="company">
                                    </div>
                                    <input id="id_input" type="hidden" name="id">
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-default">submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <script>
            function update_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);
                        }
                    }
                });
                return false;
            });

            $("#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);
                        }
                    }
                });
                return false;
            });
        </script>
    </body>
</html>

edit.php should be something like this:

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

// Check connection
if (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.




回答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
//
<table data-toggle="table" data-cache="false">
    <thead align="center">
        <tr height="35px" valign="center" bgcolor="#B0E2FF" >
            <th style="text-align:center; vertical-align:middle; width="100px">PAÍS</th>
            <th style="text-align:center; vertical-align:middle; width="250px">NOME</th>
            <th style="text-align:center; vertical-align:middle; width="300px">EMPRESA</th>
            <th style="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th>
        </tr>
    </thead>
    <? while($result = mysql_fetch_array($limite)){ ?>
    <tbody>
        <tr>
            <td style="display:none" align="center"><?=$result['id']; $_SESSION=$result['id'];?></td>
            <td style="vertical-align:middle;"> <?=$result['pais']?></td>
            <td style="vertical-align:middle;"> <?=$result['nome']?></td>
            <td style="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td>
            <td style="width:20px">

            //Some Changes Here.. check it

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

//Add this code.
<div id="form_modal" class="modal fade" aria-hidden="true">
    <div class="modal-dialog">
        <div class="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');
        });
        return false;
    });
    $('.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

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


来源:https://stackoverflow.com/questions/32721907/creating-a-crud-using-php-bootstrap-modal-mysql-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!