Skip to content

Commit

Permalink
add video view feature
Browse files Browse the repository at this point in the history
  • Loading branch information
kuldp18 committed Mar 25, 2024
1 parent 0e4d93b commit 1126286
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
39 changes: 39 additions & 0 deletions models/videos.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,42 @@ function fetch_video_views(object $pdo, int $video_id): int
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result["video_views"];
}

// check if current user has viewed the video

function has_user_viewed_video(object $pdo, int $video_id, int $user_id): bool
{
$query = "SELECT * FROM user_video_stats WHERE video_id = :video_id AND user_id = :user_id";
$stmt = $pdo->prepare($query);
$stmt->bindParam(":video_id", $video_id, PDO::PARAM_INT);
$stmt->bindParam(":user_id", $user_id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if ($result === false) {
return false;
}

return true;
}


// increment video views
function increment_video_views(object $pdo, int $video_id, int $user_id): void
{
if ($user_id !== null) {
if (!has_user_viewed_video($pdo, $video_id, $user_id)) {
$query = "UPDATE video_ratings SET video_views = video_views + 1 WHERE video_id = :video_id";
$stmt = $pdo->prepare($query);
$stmt->bindParam(":video_id", $video_id, PDO::PARAM_INT);
$stmt->execute();

// Insert user_video_stats record to mark the video as viewed by the user
$query = "INSERT INTO user_video_stats (video_id, user_id) VALUES (:video_id, :user_id)";
$stmt = $pdo->prepare($query);
$stmt->bindParam(":video_id", $video_id, PDO::PARAM_INT);
$stmt->bindParam(":user_id", $user_id, PDO::PARAM_INT);
$stmt->execute();
}
}
}
6 changes: 6 additions & 0 deletions pages/video_page.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@
$username = fetch_username_from_video_id($pdo, $current_video_id);
$average_rating = fetch_average_rating($pdo, $current_video_id);
$video_views = fetch_video_views($pdo, $current_video_id);

$current_user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

if ($current_user_id !== null) {
increment_video_views($pdo, $current_video_id, $current_user_id);
}
?>
<main class="player">
<video class="player__video video-js" controls preload="auto" width="650" height="300" poster="../uploads/thumbnails/<?php echo $video['video_thumbnail']; ?>" data-setup="{}">
Expand Down

0 comments on commit 1126286

Please sign in to comment.