0

Code on the index page where a list of videos is loaded from database:

<?php
   ini_set('display_errors', 1);
   mysqli_set_charset($link, 'utf8mb4');
   $query="SELECT * FROM videos";
   $result=mysqli_query($link,$query) or die (mysqli_error($link));

   while($row=mysqli_fetch_assoc($result))
        {
          echo '<div class=\"3u 12u(medium)\">';
          echo '<section class=\"box feature\">';
          echo '<p id="video_' . $row['v_id'] . '" class="videos">'.$row['v_url'].'</p>';
          echo '<p>'.$row['v_title'].'</p>';
          echo '<p>'.$row['v_date'].'</p>';
          echo '<p>'.$row['v_hits'].'</p>';
          echo '</section></div>';
        }
?>

<script>
    $(".videos").click(function(){
    id = this.id;
    video_id = id.substring(id.lastIndexOf('_')+1,id.length);

    //ajax call
    $.ajax({
    type: "GET",
    url: "update_video_counter.php",
    data: 'video_id=' + video_id,
    cache: false,
    success: function (html) {
    }
    });
    });

</script>

And then the update_video_counter.php page:

<?php

  $id = $_GET["video_id"];
  ini_set('display_errors', 1);
  mysqli_set_charset($link, 'utf8mb4');
  $query="UPDATE videos SET v_hits = v_hits + 1 WHERE v_id = $id";

?>

Now I'm not very experienced with Ajax/JQuery, but it looks good to me. It's not incrementing whatsoever though, but if I try to manually query in the database to check if the used query is correct, it's working just fine.

Michael
  • 93
  • 1
  • 8

1 Answers1

0

I think all you need to do is execute the query. You also should use prepared statements or cast integer values to ints so you don't get injected.

$id = (int)$_GET["video_id"];
ini_set('display_errors', 1);
mysqli_set_charset($link, 'utf8mb4');
$query="UPDATE videos SET v_hits = v_hits + 1 WHERE v_id = $id";
mysqli_query($query);

Additional information on SQL injections:

How can I prevent SQL injection in PHP?
http://php.net/manual/en/security.database.sql-injection.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29

Community
  • 1
  • 1
chris85
  • 23,846
  • 7
  • 34
  • 51