PHP将文件通信更改为数据库通信

时间:2013-01-12 10:13:07

标签: php database file pdo

此脚本是Net tuts+上的一个开源教程,但我无法弄清楚如何更改脚本以连接数据库而不是附加文档的文本文件。

脚本在这里,我理解发生了什么...但我担心我可能不得不重新编程所有内容或编写大量额外的代码,所以在我开始这样做之前我想知道是否有一种更简单的方法可以更改此信息。有关信息,我使用PDO和隐藏的config.php文件进行数据库连接,使用$conn作为PDO-DB访问。

使用课程:

$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();

评级等级:

class ratings
{
    private $data_file = './ratings.data.txt';
    private $widget_id;
    private $data = array();


    function __construct($wid)
    {
        $this->widget_id = $wid;

        $all = file_get_contents($this->data_file);

        if ($all) {
            $this->data = unserialize($all);
        }
    }
    public function get_ratings()
    {
        if ($this->data[$this->widget_id]) {
            echo json_encode($this->data[$this->widget_id]);
        } else {
            $data['widget_id']    = $this->widget_id;
            $data['number_votes'] = 0;
            $data['total_points'] = 0;
            $data['dec_avg']      = 0;
            $data['whole_avg']    = 0;
            echo json_encode($data);
        }
    }
    public function vote()
    {
        # Get the value of the vote
        preg_match('/rate_([1-5]{1})/', $_POST['clicked_on'], $match);
        $vote = $match[1];

        $ID = $this->widget_id;
        # Update the record if it exists
        if ($this->data[$ID]) {
            $this->data[$ID]['number_votes'] += 1;
            $this->data[$ID]['total_points'] += $vote;
        }
        # Create a new one if it doesn't
        else {
            $this->data[$ID]['number_votes'] = 1;
            $this->data[$ID]['total_points'] = $vote;
        }

        $this->data[$ID]['dec_avg']   = round($this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1);
        $this->data[$ID]['whole_avg'] = round($this->data[$ID]['dec_avg']);


        file_put_contents($this->data_file, serialize($this->data));
        $this->get_ratings();
    }

    # ---
    # end class
}

2 个答案:

答案 0 :(得分:1)

似乎有两点可以导入/导出类ratings的数据。

1)导入constructor,您在其中读取文件并将数据反序列化为名为data的类字段。

2)在函数vote()中导出,将序列化的data放入所需的文件中。

另外,你有一个Reporter,它是get_ratings()

您可以使用多种方法,但我建议为private $dbObject类添加一个ratings字段,该字段应该是在构造函数中初始化的PDO对象。 Learn how to initialize and create a PDO connection.创建两个私有函数来封装ratings中的数据库导入和导出过程,并在第1点和第2点调用它们。Learn how to prepare and execute a database command with PDO.您还应该检查PDO::fetch是否检索数据结果。

您也可以将数据库通信封装(委托)到另一个类中,并在ratings中使用它,这将是一个更好的抽象。

答案 1 :(得分:1)

这只是一个SIM卡。关于如何,希望能帮到你。

<?
class Vote
{
    private $_db;

    public function __construct() {
        // needs a db class
        $this->_db = DB::getInstance();
        // open connection or use existing
        $this->_db->connected or $this->_db->connect();
    }

    public function sum() {
        // get id securely or set it as NULL (@ makes it NULL silently)
        @ $ID = (int) $_POST['ID'];
        // Expr: if id !== null and id !== 0
        if ($ID) {
            // simply fetch all votes 
            return $this->_db->fetch("
                        SELECT SUM(`vote_point`) AS sums 
                        FROM `votes`
                        WHERE `ID` = $ID
                        ORDER BY sums");
        }
    }

    public function insert() {
        // get id securely or set it as NULL (@ makes it NULL silently)
        @ $ID = (int) $_POST['ID'];
        // Expr: if id !== null and id !== 0
        if ($ID) {
            // get vote point securely or set it as NULL
            $votePoint = !isset($_POST['votePoint']) ? NULL : intval($_POST['votePoint']);
            // vote point is number, so not NULL?
            if (is_int($votePoint)) {
                $this->_db->query("
                    INSERT INTO `votes` (`ID`, `vote_point`) 
                    VALUES ($ID, $votePoint)");
            }
            // yield last inserted row id (ID)
            return $this->_db->insertId();
        }
    }
}