0

I have a web page where after connecting to and selecting courses from the database, the courses are displayed with a link to view each course as below:

<div class="col-md-4">

    //query db action and assign the query to $result
    $result = $dbcon->query($query);

    if($result -> num_rows > 0){

        //If courses are available(rows > 0), fetch and display them

        while($row = $result->fetch_object()){

            echo '<h2>'.$row->course_title.'</h2';

            echo '<p>'.$row->course_description.'</p>';

            echo '<a href="view.php?action=view&t='. $row->course_id.'">View Course</a>';
        }
    }

</div>

And this is the code for view.php page:

if(isset($_GET['action']) && $_GET['action'] == "view"){

    //Assign var $id to the id from the _GET array
    $id = $_GET['t'];

    //Use the $id to fetch course details from the database
    $query = ("SELECT * FROM courses WHERE course_id = '$id'");

    //Query the db action
    $result = $db_connect->query($query);

    $rows = mysqli_num_rows($result);

    if($result && $rows > 0){

        while($row = $result->fetch_object()){

            echo '<div class="col-md-10">';

                echo '<h1>'.$row->course_title.'</h1>';

                echo '<p>'.$row->course_description.'</p>';

                echo '<div class="col-md-6"><span class="inline-elm">'.$row->course_subject.'</div>';

                echo '<div class="col-md-6"><span>'.$row->course_level.'</p></div>'</div>';
         }
     }
}

My problem is that I'm not sure whether this is proper and of course, safe to do or there is a safer/proper way to do it. Will really appreciate your answers. Thanks

Nayi
  • 65
  • 1
  • 10

1 Answers1

0

It's fine to pass ids inside urls, but they should be handled like any other data, ie properly sanitized, validated and escaped. A prepared statement is a good way to do this. At the very least, here, since you expect an int, you can do:

$id = intval($_GET['t']);

Note that prepared statements do not protect against XSS vulnerabilities which would occur if doing "echo $id" without wrapping it in htmlspecialchars. Input sanitization is always nice, if it's an int, stick an intval on it! You never know...

bobflux
  • 11,123
  • 3
  • 27
  • 27