我在WordPress中有一個依賴外部數據庫的自定義頁面模板,並且使用wpdb類來實現此目的。使用WordPress中的wpdb類訪問外部數據庫
這是我的代碼:
<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 -->
嗯,我想知道,這是做正確的方式。實際上,安全方面或任何「其他」都是明智的。
從頁面模板本身進行外部數據庫調用感覺有點簡單。我是否應該在某些外部文件上註冊這些功能,然後在模板中使用它們?
我可以輸入這個值爲area_code或student_id嗎? 「'null或1 = 1; drop table users; --'」確保輸入信息在[bobby tables](https://xkcd.com/327/)到達您的頁面之前已'消毒'。 – coderatchet
@thenaglecode他們都很好的消毒,我只是張貼了一部分代碼(:但是感謝您的關注,雖然! –