简体   繁体   English

如何使用 PHP 和 AJAX 删除/编辑 sql 条目?

[英]How to delete/edit sql entry using PHP and AJAX?

I'm learning PHP and SQL and as exercise I'm working on a page that is actually something like admin panel for a website that lists movies.我正在学习 PHP 和 SQL,作为练习,我正在处理一个页面,该页面实际上类似于列出电影的网站的管理面板。 I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.我正在使用 lampp 和 phpmyadmin,其中我创建了一个简单的数据库,其中包含两个表、电影列表和用户列表。

Because I'm beginner and my code is probably messy, I'm describing what I tried to achieve.因为我是初学者并且我的代码可能很乱,所以我正在描述我试图实现的目标。 There's login.php page where the only functionality is typing username and password.有 login.php 页面,其中唯一的功能是输入用户名和密码。 If info matches info from SQL table, user proceeds to adminpanel.php.如果信息与 SQL 表中的信息匹配,则用户继续访问 adminpanel.php。

This page should load a list of movies and create a table with that data.此页面应加载电影列表并使用该数据创建一个表。 At the end of each row I want two buttons, edit and delete.在每一行的末尾我想要两个按钮,编辑和删除。 What I'm trying to achieve is to delete current row where delete button is clicked, for delete button.我想要实现的是删除单击删除按钮的当前行,用于删除按钮。 Edit button should show hidden form just for the row where button was clicked.编辑按钮应该只为单击按钮的行显示隐藏表单。 This form would contain button that actually updates data in SQL table after filling form and clicking the button.此表单将包含在填写表单并单击按钮后实际更新 SQL 表中数据的按钮。 (I haven't added function that shows form yet, I care about buttons much more) Form for adding movies at the end of the file works. (我还没有添加显示表单的功能,我更关心按钮)在文件末尾添加电影的表单有效。

Here's adminpanel.php这是 adminpanel.php

    <html>
    <head>
        <script src="https://code.jquery.com/jquery-3.3.1.js" 
                integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
                crossorigin="anonymous">
        </script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
        <script type="text/javascript" src="changes.js"></script>
        <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>

        <style type="text/css">

            *{text-align: center;}

            .skriveni_input{
                display: none;
            };

        </style>
    </head>

<?php 
    require_once('connection.php');

    if(!isset($_POST['btnlogin'])){
            exit;
        } 

        $username = $_POST['username'];
        $password = $_POST['password'];
        $query = "SELECT usrname,password FROM usrs WHERE usrname='$username' AND password='$password' ";

        $res = mysqli_query($conn,$query);
        $rows = mysqli_num_rows($res);

        if($rows == 1){
            echo "Welcome ".$_POST['username']."<br><br>";
        } else {
            echo "<script>
                alert('Wrong login info');
                window.location.href='login.php';
                </script>";
            exit;
        }

        $query = "SELECT * FROM movies";
        $result = $conn->query($query);

        echo "<table align = center cellspacing = 0 border = 0;><thead><tr><th>Name</th><th>Year</th><th>Genre</th></tr></thead><tbody>";
        while ($row = mysqli_fetch_array($result)) {
            echo "<tr>";
            echo '<td id="row_id" style="display:none;" value="'.$row["movie_id"].'">'.$row["movie_id"].'</td>';
            echo '<td>'.$row["name"].'</td>';
            echo '<td>'.$row["year"].'</td>';
            echo '<td>'.$row["genre"].'</td>';
            echo '<td><input type="submit" name="edit" value="edit" data-index="' . $row['movie_id'] . '" class="btnedit" id="btnedit"></input></td>';
            echo '<td><input type="submit" name="delete" value="delete" class="btndlt" id="btndlt"></input></td>';
            echo "</tr>";
            echo "<tr>
                      <td><input type='text' class='hidden_input' id='hidden_name" . $row['movie_id'] . "'placeholder='hidden name'></input></td>
                      <td><input type='text' class='hidden_input' id='hidden_year" . $row['movie_id'] . "'placeholder='hidden year'></input></td>
                      <td><input type='text' class='hidden_input' id='hidden_genre" . $row['movie_id'] . "'placeholder='hidden genre'></input></td>
                 </tr>";
        }
        echo "</tbody></table>";
?>

    <h3>Add movie form: </h3>
    <form action="" method="POST">
        <label for="movie_name">Movie name : </label>
        <input type="text" name="movie_name" id="movie_name">
        <br><br>
        <label for="movie_year">Year: </label>
        <input type="text" name="movie_year" id="movie_year">
        <br><br>
        <label for="movie_genre">Genre: </label>
        <input type="text" name="movie_genre" id="movie_genre">
        <br><br>
        <input type="submit" name="submit_movie" id="submit_movie" value="Submit"> 
    </form>

</html>

Here's my javascript file with ajax calls:这是我的带有 ajax 调用的 javascript 文件:

$(document).ready(function(e){

    $('#submit_movie').click(function(e){
        e.preventDefault();
        var movie_name = $('#movie_name').val();
        var movie_year = $('#movie_year').val();
        var movie_genre = $('#movie_genre').val();

        $.ajax({
            type: 'POST',
            data: {movie_name:movie_name, movie_year:movie_year, movie_genre:movie_genre},
            url: "insert.php",
            success: function(result){
                        alert('Movie ' + movie_name + ' (' + movie_year + ')' +' added successfully.');
                        document.location.reload();
                    }
        })
    });

    $('.btnedit').click(function(e){
        var id = $(this).parent().prev().prev().prev().prev().html();
        alert(id);
        //unfinished function
    })

    $('.btndlt').click(function(e){
        var id = $(this).parent().prev().prev().prev().prev().prev().html();
        e.preventDefault();
        $.ajax({
            type: 'POST',
            data: {id:id},
            url: 'delete_row.php',
            success: function(result){
                alert('Successfully deleted.');
                document.location.reload();
            }
        })
    })

});

Here's php page for adding a movie, insert.php (this one works, posting it just for more information) :这是用于添加电影的 php 页面,insert.php(这个有效,发布它只是为了获取更多信息):

<?php 
require_once('connection.php');

if($_REQUEST['movie_name']){
    $name = $_REQUEST['movie_name'];
    $year = $_REQUEST['movie_year'];
    $genre = $_REQUEST['movie_genre'];

    $sql = "INSERT INTO movies(name, year, genre) VALUES ('$name','$year','$genre')";
    $query = mysqli_query($conn, $sql);

}


?>

Here's delete_row.php file for deleting entry with delete button:这是用于使用删除按钮删除条目的 delete_row.php 文件:

<?php 
require_once('connection.php');

    $id = $_REQUEST['id'];

    if(isset($_REQUEST['delete'])){
        $sql = "DELETE FROM `movies` WHERE movie_id = $id";
        $query = mysqli_query($conn, $sql);
    }
 ?>

As you can probably see I was all over the place with php and ajax because I tried to implement multiple solutions or mix them to solve the problem.正如您可能看到的那样,我到处都是 php 和 ajax,因为我试图实现多种解决方案或混合使用它们来解决问题。 At this stage when I click delete button I get alert message that says erasing is successful and adminpanel.php reloads with list of movies.在这个阶段,当我单击删除按钮时,我收到警告消息,说擦除成功并且 adminpanel.php 重新加载了电影列表。 However the movie is still there and in SQL database.然而,电影仍然存在并且在 SQL 数据库中。

When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.当我尝试调试 delete_row.php 时,我发现索引“id”每次都未定义,即使我认为我是通过 ajax 调用传递它的。

Edit编辑

I should've said that security is not my concern right now, I do this exercise just for functionalities I described.我应该说安全不是我现在关心的问题,我做这个练习只是为了我描述的功能。 :) Security is my next step, I am aware this code is not secure at all. :) 安全是我的下一步,我知道这段代码根本不安全。

When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.当我尝试调试 delete_row.php 时,我发现索引“id”每次都未定义,即使我认为我是通过 ajax 调用传递它的。

The reason this happens is probably because you're accessing delete_row.php directly through the browser, and because the form is not submitted (it will later through ajax) the $_REQUEST variable will always be undefined.发生这种情况的原因可能是因为您直接通过浏览器访问delete_row.php ,并且因为未提交表单(稍后将通过 ajax)$ delete_row.php变量将始终未定义。

When debugging $_REQUEST (or $_POST) variables in the future, you should use Postman where you can actually request that php file sending your own POST arguments.将来在调试 $_REQUEST(或 $_POST)变量时,您应该使用Postman ,您可以在其中实际请求 php 文件发送您自己的 POST 参数。

On your specific code, the query will never run because of this line:在您的特定代码上,查询将永远不会运行,因为这一行:

if(isset($_REQUEST['delete']))

Which is checking for a delete variable that was never sent in the first place, hence will always resolve false这是检查从未发送过的delete变量,因此将始终解析为false

Use this code instead on delete_row.php:在 delete_row.php 上使用此代码:

<?php 
require_once('connection.php');
    if(isset($_REQUEST['id'])){
        $id = $_REQUEST['id'];
        $sql = "DELETE FROM `movies` WHERE movie_id = $id";
        $query = mysqli_query($conn, $sql);
    }
 ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM