Accessing external database using the wpdb class in WordPress

Viewed 1985

I have a custom page template in WordPress that is relying on an external database, and which is using the wpdb class for this purpose.

This is my code:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
    </header><!-- .entry-header -->

<?php

class StudentsDatabase
{
    private $db;
    public function __construct() {
        try {
            $this->db = new wpdb(DB_USER, DB_PASSWORD, 'students_db', DB_HOST);
            $this->db->show_errors();
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
    public function getStudentById($student_id)
    {
        return $this->db->get_results("SELECT * FROM `students` WHERE id=$student_id");
    }
    public function getSchoolByAreaCode($area_code)
    {
        return $this->db->get_results("SELECT * FROM `schools` WHERE area_code=$area_code;--");
    }

}
$Students_DB = new StudentsDatabase();
$student_one = $Students_DB->getStudentById(1);
$school_one = $Students_DB->getSchoolByAreaCode(1);

?>
<div class="entry-content">
    <?php

    //do something with $student_one and $school_one ...

    the_content();

    ?>
</div><!-- .entry-content -->

Well, I was wondering if this is the right way to do it. Security-wise or any 'other'-wise actually.

It feels kinda sketchy to make external db calls from within the page's template itself. Should I register these functions on some external file and then just use them inside the template?

3 Answers
Related