0

このスクリプトはNet tuts+のオープン ソース チュートリアルですが、ドキュメントに添付されたテキスト ファイルではなくデータベースに接続するようにスクリプトを変更する方法がわかりません。

スクリプトはここにあり、何が起こっているのか理解しています...しかし、ほとんどすべてを再プログラムするか、多くの追加コードを書く必要があるのではないかと心配しているので、それを始める前に、これを変更する簡単な方法..情報については、PDO-DBアクセスとしてconfig.php使用するデータベース接続用のPDOと隠しファイルを使用しています。$conn

クラスの使用:

$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
}
4

2 に答える 2

1

クラスのデータをインポート/エクスポートするポイントは 2 つありますratings

1)constructorファイルを読み込み、データを という名前のクラス フィールドにシリアル化解除しますdata

2)vote()シリアルdata化されたファイルを目的のファイルに配置する関数でエクスポートします。

また、Reporter があります。これはget_ratings().

いくつかの方法がありますが、コンストラクターで初期化された PDO オブジェクトであるクラスのprivate $dbObjectフィールドを追加することをお勧めします。PDO 接続を初期化して作成する方法を学びます。2 つのプライベート関数を作成して、データベースのインポートおよびエクスポート手順を 内にカプセル化し、それらをポイント 1 および 2 で呼び出します。PDO を使用してデータベース コマンドを準備および実行する方法を学びます。結果からデータを取得することも確認する必要があります。ratingsratingsPDO::fetch

また、データベース通信を別のクラスにカプセル化 (デリゲート) し、それを で使用することもできますratings。これは、より優れた抽象化になります。

于 2013-01-12T10:29:01.160 に答える
1

これはただのシムです。方法について、お役に立てれば幸いです。

<?
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();
        }
    }
}
于 2013-01-12T15:24:23.053 に答える