【发布时间】:2013-01-12 10:13:06
【问题描述】:
此脚本是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
}
【问题讨论】:
-
你为什么用丑陋的
var关键字?这已被弃用,这样$data_file属性将被定义为公共。 -
正如我在上面的文字中描述的 - 这是一个来自 Net tuts+ 的开源教程..
-
看起来源代码没有修改,但是文章本身已经修改了,看看文章中说“我们首先要看的是类的开始,更具体地说,是构造函数。” 顺便说一句,我下载了它,不幸的是它的代码很丑。