0

I want a simple non-MySQL PHP script that allows viewers to vote up or vote down a page. If it has to be MySQL database driven, then that's just how it has to be. Ideally, not though.

So basically if you were to view source of this page in a web browser it would look something like this:

<h2>Stack Overflow Is Cool</h2>
<span id="author-info-etc">Written by Ben Dover on 01-01-2012 (+12) | (-3) Total Rank: +9</span>
<p>Once upon a time there was this really cool website called Stack Overflow where amazing people would help answer questions asked by people who destroyed their keyboards by throwing them against their computer screen in an act of utter frustration and despair.</p>

And the source file would look like this:

<span id="author-info-etc">Written by <?php echo $authorname; ?> on <?php echo $pubDate; ?> <?php include ('pagevotescript.php'); ?></span>

Could someone help me to create this PHP script?

4

5 回答 5

2

如果你想要一个可靠的投票系统,你需要使用 MySQL 等数据库来存储投票。否则,你的 web 应用程序如何知道一个页面收到了多少票?

您的数据库结构可能如下所示:

页面

page_id | page_name
-------------------
1       | My Page
2       | Test

用户

user_id | user_name
-------------------
1       | John     
2       | Sara
3       | Tom

投票

vote_id | user_id | page_id | vote_weight
-----------------------------------------
1       | 1       | 1       |  1
2       | 1       | 2       | -1
3       | 2       | 2       |  1
4       | 3       | 1       |  1

当用户投票时:

  1. 检查他们是否已经在页面上投票。
  2. 如果是这样,要么拒绝他们再次投票,要么更新他们现有的投票。
  3. 如果他们没有在相关页面上投票,请插入新的投票。
于 2012-10-04T16:39:00.070 回答
1

将页面数据存储在 MySQL 中是最简单的,并且只有一个名为 votes 的列。这样,您可以同时显示页面并拉取投票,并且可以在用户交互时轻松地提高/降低投票。

如果没有 MySQL,您需要将值存储在某个文件中。你可以有 about-us.php,然后是 about-us.php.txt,其中 txt 文件将是一个简单的 # 可以检索,然后更改和重置。像这样的东西:

// Open file for reading and writing
$fp = fopen('about-us.php.txt', 'w+');

//Retrieve contents of file as integar
$count = (int) fread($fp, filesize('about-us.php.txt'));

// Take the count and up it by 1
$count++;

// Write the changes
fwrite($fp, $count);

// Close the file
fclose($fp);
于 2012-10-04T16:39:33.367 回答
0

您希望拥有一个包含用户和帖子的数据库。用户应该能够对帖子进行投票,增加或减少用户的“声誉”计数。要存储所有这些信息,您已经需要一个数据库。

如果您仍然想将“投票”信息存储在 mysql 数据库之外的其他东西中,那么有很多选择。text fileNoSQLCouchdb和许多其他选项。

您将更容易学习如何与数据库进行通信,然后执行诸如将信息存储在文件中之类的事情。而且由于 mysql 是最常用的数据库,这将是一个相当明智的选择。

PS:如果你开始学习 mysql,你绝对不应该开始使用 PHPmysql_函数,而应该使用PDO之类的东西来规避SQL 注入。

于 2012-10-04T16:39:46.557 回答
0

您需要一种在会话之间持久保存数据的方法,因此您需要一个数据库,如果您不想安装 mysql,我认为 PHP 的最新版本内置了sqlite支持。

于 2012-10-04T16:38:57.997 回答
0

技术含量低的方法是使用带有 PHP 的键值存储来存储您的值。一个例子是dba_*PHP 中的函数,如dba_open,它创建一个行为类似于任何常规文件的单文件数据库,不需要服务器。

例子:

$db = dba_open("stats", "r", "gdbm");
$count = dba_fetch("/page/path", $db);
dba_insert("/page/path", $count + 1, $db);

请注意,这将受到微妙的竞争条件的影响,其中两个或多个同时请求将获取并保存相同的增量值。使用适当的数据库,甚至是嵌入式 SQLite,将是一个更好的主意。

于 2012-10-04T17:49:51.197 回答