1

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. I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.

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. If info matches info from SQL table, user proceeds to 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. (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

    <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:

$(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 
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:

<?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. 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. However the movie is still there and in SQL database.

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.

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
trbste
  • 27
  • 9
  • 2
    Your script is wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's – RiggsFolly Aug 22 '18 at 15:16
  • 1
    You should also never store passwords in clear text like that. You should always only store password hashes. Have a look at PHP's [password_hash()](http://php.net/manual/en/function.password-hash.php) and [password_verify()](http://php.net/manual/en/function.password-verify.php). – M. Eriksson Aug 22 '18 at 15:17
  • Is `var id = $(this).parent().prev().prev().prev().prev().prev().html();` actually defining `id`? – AmmoPT Aug 22 '18 at 15:34
  • My bad, I should've said that security is not my priority in this exercise. I am aware of the problems but thank you for your feedback, I appreciate it. :) @AmmoPT Yes, that is variable that should define id, I stored it as value of hidden td with id row_id . – trbste Aug 22 '18 at 15:46
  • 1
    @trbste I know it's supposed to, but is it actually working? If you `console.log(id)` right afterwards, before the ajax call, is it defined? – AmmoPT Aug 22 '18 at 15:50
  • Also, on `delete_row.php` when is `if(isset($_REQUEST['delete']))` ever gonna be true? 'delete' parameter is not being sent. – AmmoPT Aug 22 '18 at 16:00
  • @AmmoPT I checked it out, it is working properly. console.log(id) prints id of the row where function was called. – trbste Aug 22 '18 at 16:01
  • @AmmoPT I think you're on point with comment about `if(isset($_REQUEST['delete']))` I'm not sure how to actually send it apart from sending from form with post or get method. – trbste Aug 22 '18 at 16:02

1 Answers1

1

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.

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.

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.

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

Use this code instead on 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);
    }
 ?>
AmmoPT
  • 958
  • 1
  • 9
  • 16
  • how is this different from what OP posted? And if it is different, how is this supposed to fix OP's issue? – Lelio Faieta Aug 22 '18 at 16:06
  • This worked just as I wanted to. Thank you. Can you please explain shortly what did I do wrong so I can learn for future? – trbste Aug 22 '18 at 16:07
  • @AmmoPT Also, could I ask you what would my update function look like? Should I go with similar logic, just replace sql query with UPDATE one? – trbste Aug 22 '18 at 16:10
  • @trbste I edited the post to provide more clarification, let me know if that's good enough. – AmmoPT Aug 22 '18 at 16:11
  • @LelioFaieta I edited the post to provide more clarification, let me know if that's good enough. – AmmoPT Aug 22 '18 at 16:13
  • 1
    @AmmoPT Your answer is very helpful. Thanks for letting me know about Postman, I will check it out. – trbste Aug 22 '18 at 16:27