使用 PHP 和 MySQL 的投票和投票系统

迷南。 2023-09-28 01:26 239阅读 0赞

Poll and Voting System with PHP and MySQL

在本教程中,我们将使用 PHP 和 MySQL 创建一个安全的投票和投票系统,您可以使用它以一种固执己见的方式与您的听众交流。

您将学习如何创建投票、实施投票系统、删除投票以及填充已发布投票的列表。

在投票创建阶段,我们将能够指定任意数量的答案,因为所有答案都将存储在单独的数据库表中。一个表将专用于投票,我们可以存储与投票相关的数据(标题、描述等),另一个用于存储所有答案,然后将两个表关联以填充列表。

高级包包括附加功能和源代码的下载链接。

内容

  1. 入门

    1. 您将在本教程中学到什么
    2. 要求
    3. 文件结构和设置
  2. 创建数据库和设置表
  3. 创建样式表 (CSS3)
  4. 使用 PHP 创建投票和投票系统

    1. 功能
    2. 索引页
    3. 创建页面
    4. 投票页面
    5. 结果页面
    6. 删除页面

1. 入门

在我们开始编写民意调查和投票系统之前,需要满足一些要求。我们需要安装开发工具并为我们的应用设置文件结构。

1.1。您将在本教程中学到什么

  • 表单设计— 使用 HTML5 和 CSS3 设计投票和投票应用程序。
  • 投票系统— 使用 PHP 和 MySQL 创建一个有效的投票系统(创建投票、删除投票和查看投票)。
  • 投票系统——每次投票将包含用户可以选择投票并随后查看结果的答案。
  • MySQL 数据库交互— 使用 PHP PDO 接口与 MySQL 数据库交互。在创建阶段输入的所有数据都将存储在 MySQL 数据库中。
  • 基本模板系统——我们将为我们的应用程序创建一个基本模板系统,其中包括页眉和页脚功能。然后可以在我们创建的所有页面上实现这些功能。这样我们就不必一遍又一遍地编写相同的代码。

1.2. 要求

  • 下载并安装XAMPP — XAMPP 是一个 Web 服务器,其中包括 Web 开发人员的基本软件(PHP、MySQL、Apache 等)。如果您已经安装了开发服务器,请跳过此步骤。

1.3. 文件结构和设置

导航到您的 XAMPP htdocs目录(通常位于C:\xampp\htdocs)并创建以下文件和目录:

文件结构

\— phppoll
|— functions.php
|— index.php
|— create.php
|— vote.php
|— result.php
|— delete.php
|— style.css

每个文件将包含以下内容:

  • functions.php — 函数文件将包含模板和数据库连接函数。
  • index.php — 索引页面将包含已发布的民意调查列表和导航按钮。
  • create.php — 创建页面将包含表单输入字段,我们可以使用它来创建新的投票。
  • vote.php — 投票页面将包含投票答案和投票选项。
  • result.php — 结果页面将显示指定投票的结果,而每个答案将显示投票数和百分比条。
  • style.css — 投票和投票系统的样式表 (CSS3)。

2. 创建数据库和设置表

如果你已经安装了 XAMPP,你可以使用phpMyAdmin创建 MySQL 数据库。虽然,您需要确保启动 Web 服务器:打开 XAMPP 控制面板并单击 Apache 和 MySQL 的启动按钮。

  • 在浏览器中导航到http://localhost/phpmyadmin/
  • 单击顶部的SQL选项卡并执行以下 SQL 语句:

    CREATE TABLE IF NOT EXISTS polls (

    1. `id` int(11) NOT NULL AUTO_INCREMENT,
    2. `title` text NOT NULL,
    3. `description` text NOT NULL,
    4. PRIMARY KEY (`id`)

    ) ;

    INSERT INTO polls (id, title, description) VALUES (1, ‘What’’s your favorite programming language?’, ‘’);

    CREATE TABLE IF NOT EXISTS poll_answers (

    1. `id` int(11) NOT NULL AUTO_INCREMENT,
    2. `poll_id` int(11) NOT NULL,
    3. `title` text NOT NULL,
    4. `votes` int(11) NOT NULL DEFAULT '0',
    5. PRIMARY KEY (`id`)

    ) ;

    INSERT INTO poll_answers (id, poll_id, title, votes) VALUES (1, 1, ‘PHP’, 0), (2, 1, ‘Python’, 0), (3, 1, ‘C#’, 0), (4, 1, ‘Java’, 0);

在 phpMyAdmin 中,我们的数据库应如下所示:

832eafb679d25820a25c4c056338cbe5.png

每个表和与其关联的列的摘要:

  • 民意调查表——该表将包含与我们创建的民意调查相关的信息(标题和描述)。

    • id — 投票的唯一 ID,将自动递增。
    • title — 投票的标题,可以是问题等。
    • description — 轮询的描述,在创建阶段是可选的。
  • poll_answers表 - 该表将包含我们创建的民意调查的所有答案。

    • id — 唯一 ID,将自动递增。
    • poll_id — 投票 ID,将与 polls 表中的id列相关联。这就是我们可以关联两个表的方式。
    • title — 投票答案的标题。
    • 票数——答案的票数。

为确保数据库已成功导入,您可以检查phpMyAdmin — 单击左侧导航面板中的数据库名称,您应该会看到以下内容:

4ba691820edf39cf73da4da7d8021e06.png

3. 创建样式表 (CSS3)

样式表将格式化我们的投票和投票系统的结构,并使其看起来更有吸引力。将以下 CSS 代码添加到style.css文件中:

  1. * {
  2. box-sizing: border-box;
  3. font-family: -apple-system, BlinkMacSystemFont, "segoe ui", roboto, oxygen, ubuntu, cantarell, "fira sans", "droid sans", "helvetica neue", Arial, sans-serif;
  4. font-size: 16px;
  5. -webkit-font-smoothing: antialiased;
  6. -moz-osx-font-smoothing: grayscale;
  7. }
  8. body {
  9. background-color: #FFFFFF;
  10. margin: 0;
  11. }
  12. .navtop {
  13. background-color: #3f69a8;
  14. height: 60px;
  15. width: 100%;
  16. border: 0;
  17. }
  18. .navtop div {
  19. display: flex;
  20. margin: 0 auto;
  21. width: 1000px;
  22. height: 100%;
  23. }
  24. .navtop div h1, .navtop div a {
  25. display: inline-flex;
  26. align-items: center;
  27. }
  28. .navtop div h1 {
  29. flex: 1;
  30. font-size: 24px;
  31. padding: 0;
  32. margin: 0;
  33. color: #ecf0f6;
  34. font-weight: normal;
  35. }
  36. .navtop div a {
  37. padding: 0 20px;
  38. text-decoration: none;
  39. color: #c5d2e5;
  40. font-weight: bold;
  41. }
  42. .navtop div a i {
  43. padding: 2px 8px 0 0;
  44. }
  45. .navtop div a:hover {
  46. color: #ecf0f6;
  47. }
  48. .content {
  49. width: 1000px;
  50. margin: 0 auto;
  51. }
  52. .content h2 {
  53. margin: 0;
  54. padding: 25px 0;
  55. font-size: 22px;
  56. border-bottom: 1px solid #ebebeb;
  57. color: #666666;
  58. }
  59. .home .create-poll {
  60. display: inline-block;
  61. text-decoration: none;
  62. background-color: #38b673;
  63. font-weight: bold;
  64. font-size: 14px;
  65. border-radius: 5px;
  66. color: #FFFFFF;
  67. padding: 10px 15px;
  68. margin: 15px 0;
  69. }
  70. .home .create-poll:hover {
  71. background-color: #32a367;
  72. }
  73. .home table {
  74. width: 100%;
  75. padding-top: 30px;
  76. border-collapse: collapse;
  77. }
  78. .home table thead {
  79. background-color: #ebeef1;
  80. border-bottom: 1px solid #d3dae0;
  81. }
  82. .home table thead td {
  83. padding: 10px;
  84. font-weight: bold;
  85. color: #767779;
  86. font-size: 14px;
  87. }
  88. .home table tbody tr {
  89. border-bottom: 1px solid #d3dae0;
  90. }
  91. .home table tbody tr:nth-child(even) {
  92. background-color: #fbfcfc;
  93. }
  94. .home table tbody tr:hover {
  95. background-color: #376ab7;
  96. }
  97. .home table tbody tr:hover td {
  98. color: #FFFFFF;
  99. }
  100. .home table tbody tr:hover td:nth-child(1) {
  101. color: #FFFFFF;
  102. }
  103. .home table tbody tr td {
  104. padding: 10px;
  105. }
  106. .home table tbody tr td:nth-child(1) {
  107. color: #a5a7a9;
  108. }
  109. .home table tbody tr td.actions {
  110. padding: 8px;
  111. text-align: right;
  112. }
  113. .home table tbody tr td.actions .view, .home table tbody tr td.actions .edit, .home table tbody tr td.actions .trash {
  114. display: inline-flex;
  115. text-align: right;
  116. text-decoration: none;
  117. color: #FFFFFF;
  118. padding: 10px 12px;
  119. border-radius: 5px;
  120. }
  121. .home table tbody tr td.actions .trash {
  122. background-color: #b73737;
  123. }
  124. .home table tbody tr td.actions .trash:hover {
  125. background-color: #a33131;
  126. }
  127. .home table tbody tr td.actions .edit {
  128. background-color: #37afb7;
  129. }
  130. .home table tbody tr td.actions .edit:hover {
  131. background-color: #319ca3;
  132. }
  133. .home table tbody tr td.actions .view {
  134. background-color: #37b770;
  135. }
  136. .home table tbody tr td.actions .view:hover {
  137. background-color: #31a364;
  138. }
  139. .update form {
  140. padding: 15px 0;
  141. display: flex;
  142. flex-flow: column;
  143. width: 400px;
  144. }
  145. .update form label {
  146. display: inline-flex;
  147. width: 100%;
  148. padding: 10px 0;
  149. margin-right: 25px;
  150. }
  151. .update form input, .update form textarea {
  152. padding: 10px;
  153. width: 100%;
  154. margin-right: 25px;
  155. margin-bottom: 15px;
  156. border: 1px solid #cccccc;
  157. }
  158. .update form textarea {
  159. height: 200px;
  160. }
  161. .update form input[type="submit"] {
  162. display: block;
  163. background-color: #38b673;
  164. border: 0;
  165. font-weight: bold;
  166. font-size: 14px;
  167. color: #FFFFFF;
  168. cursor: pointer;
  169. width: 200px;
  170. margin-top: 15px;
  171. border-radius: 5px;
  172. }
  173. .update form input[type="submit"]:hover {
  174. background-color: #32a367;
  175. }
  176. .delete .yesno {
  177. display: flex;
  178. }
  179. .delete .yesno a {
  180. display: inline-block;
  181. text-decoration: none;
  182. background-color: #38b673;
  183. font-weight: bold;
  184. color: #FFFFFF;
  185. padding: 10px 15px;
  186. margin: 15px 10px 15px 0;
  187. border-radius: 5px;
  188. }
  189. .delete .yesno a:hover {
  190. background-color: #32a367;
  191. }
  192. .poll-vote form {
  193. display: flex;
  194. flex-flow: column;
  195. }
  196. .poll-vote form label {
  197. padding-bottom: 10px;
  198. }
  199. .poll-vote form input[type="radio"] {
  200. transform: scale(1.1);
  201. }
  202. .poll-vote form input[type="submit"], .poll-vote form a {
  203. display: inline-block;
  204. padding: 8px;
  205. border-radius: 5px;
  206. background-color: #38b673;
  207. border: 0;
  208. font-weight: bold;
  209. font-size: 14px;
  210. color: #FFFFFF;
  211. cursor: pointer;
  212. width: 150px;
  213. margin-top: 15px;
  214. }
  215. .poll-vote form input[type="submit"]:hover, .poll-vote form a:hover {
  216. background-color: #32a367;
  217. }
  218. .poll-vote form a {
  219. text-align: center;
  220. text-decoration: none;
  221. background-color: #37afb7;
  222. margin-left: 5px;
  223. }
  224. .poll-vote form a:hover {
  225. background-color: #319ca3;
  226. }
  227. .poll-result .wrapper {
  228. display: flex;
  229. flex-flow: column;
  230. }
  231. .poll-result .wrapper .poll-question {
  232. width: 50%;
  233. padding-bottom: 5px;
  234. }
  235. .poll-result .wrapper .poll-question p {
  236. margin: 0;
  237. padding: 5px 0;
  238. }
  239. .poll-result .wrapper .poll-question p span {
  240. font-size: 14px;
  241. }
  242. .poll-result .wrapper .poll-question .result-bar {
  243. display: flex;
  244. height: 25px;
  245. min-width: 5%;
  246. background-color: #38b673;
  247. border-radius: 5px;
  248. font-size: 14px;
  249. color: #FFFFFF;
  250. justify-content: center;
  251. align-items: center;
  252. }

随意自定义它或使用您自己的样式表。

4. 使用 PHP 创建投票和投票系统

我们终于可以开始用 PHP 编写我们的投票和投票系统了。

4.1。功能

functions.php文件将包含模板和数据库连接函数,我们可以在我们创建的所有页面中实现它们。

编辑functions.php文件并添加:

  1. <?php
  2. function pdo_connect_mysql() {
  3. // Update the details below with your MySQL details
  4. $DATABASE_HOST = 'localhost';
  5. $DATABASE_USER = 'root';
  6. $DATABASE_PASS = '';
  7. $DATABASE_NAME = 'phppoll';
  8. try {
  9. return new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
  10. } catch (PDOException $exception) {
  11. // If there is an error with the connection, stop the script and display the error.
  12. exit('Failed to connect to database!');
  13. }
  14. }

每次我们想要连接到我们的 MySQL 数据库时,我们所要做的就是执行上面的函数,如下所示:

  1. pdo_connect_mysql();

如果您遇到与 MySQL 的连接问题,您很可能必须更新数据库变量以反映您的 MySQL 凭据和数据库名称。如果您使用 XAMPP,则不必更改变量。

之后添加:

  1. // Template header, feel free to customize it, but DO NOT INDENT THE PHP CODE
  2. function template_header($title) {
  3. // DO NOT INDENT THE BELOW PHP CODE OR YOU WILL ENCOUNTER ISSUES
  4. echo <<<EOT
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <meta charset="utf-8">
  9. <title>$title</title>
  10. <link href="style.css" rel="stylesheet" type="text/css">
  11. <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
  12. </head>
  13. <body>
  14. <nav class="navtop">
  15. <div>
  16. <h1>Voting & Poll System</h1>
  17. <a href="index.php"><i class="fas fa-poll-h"></i>Polls</a>
  18. </div>
  19. </nav>
  20. EOT;
  21. }

我们模板的标题功能,包括文档的标题部分和将出现在每个页面上的顶部导航栏。我们还包括Font Awesome库,这是一个免费的图标库(我们将在我们的应用程序中使用的图标)。

之后添加:

  1. // Template footer
  2. function template_footer() {
  3. // DO NOT INDENT THE PHP CODE
  4. echo <<<EOT
  5. </body>
  6. </html>
  7. EOT;
  8. }

模板页脚功能,基本上就是文档的结尾:关闭 HTML 标签等。

现在,如果我们想创建一个新页面,我们可以实现如下代码:

  1. <?php
  2. // examplepage.php
  3. include 'functions.php';
  4. $pdo = pdo_connect_mysql();
  5. ?>
  6. <?=template_header('Example Page')?>
  7. <p>Hello World! Welcome to my custom page!</p>
  8. <?=template_footer()?>

太棒了,对吧?现在我们不必在所有 PHP 文件中包含相同的模板函数代码和连接函数代码,因为我们所要做的就是执行该函数。

请注意,以下代码:

  1. <?=template_footer()?>

是以下的简短版本:

  1. <?php echo template_footer(); ?>

这就是我们将要使用的所有创建的函数。

4.2. 索引页

索引页面将包含所有填充的民意调查列表以及我们可以用来查看和删除民意调查的按钮。

编辑index.php文件并添加:

  1. <?php
  2. // Include the function file
  3. include 'functions.php';
  4. // Connect to MySQL
  5. $pdo = pdo_connect_mysql();
  6. // MySQL query that retrieves all the polls and poll answers
  7. $stmt = $pdo->query('SELECT p.*, GROUP_CONCAT(pa.title ORDER BY pa.id) AS answers FROM polls p LEFT JOIN poll_answers pa ON pa.poll_id = p.id GROUP BY p.id');
  8. $polls = $stmt->fetchAll(PDO::FETCH_ASSOC);
  9. ?>

上面的代码将从我们的数据库表中检索所有投票和投票答案,然后我们可以随后以 HTML 表格格式填充列表。

之后添加:

  1. <?=template_header('Polls')?>
  2. <div class="content home">
  3. <h2>Polls</h2>
  4. <p>Welcome to the home page! You can view the list of polls below.</p>
  5. <a href="create.php" class="create-poll">Create Poll</a>
  6. <table>
  7. <thead>
  8. <tr>
  9. <td>#</td>
  10. <td>Title</td>
  11. <td>Answers</td>
  12. <td></td>
  13. </tr>
  14. </thead>
  15. <tbody>
  16. <?php foreach($polls as $poll): ?>
  17. <tr>
  18. <td><?=$poll['id']?></td>
  19. <td><?=$poll['title']?></td>
  20. <td><?=$poll['answers']?></td>
  21. <td class="actions">
  22. <a href="vote.php?id=<?=$poll['id']?>" class="view" title="View Poll"><i class="fas fa-eye fa-xs"></i></a>
  23. <a href="delete.php?id=<?=$poll['id']?>" class="trash" title="Delete Poll"><i class="fas fa-trash fa-xs"></i></a>
  24. </td>
  25. </tr>
  26. <?php endforeach; ?>
  27. </tbody>
  28. </table>
  29. </div>
  30. <?=template_footer()?>

首先,我们从执行模板头函数开始上面的代码(模板头()),然后使用foreach循环迭代轮询并将它们填充到 HTML 表中,最后,我们使用模板页脚函数 (模板页脚()).

通过表中的 HTML 锚链接,您可以看到我们将传递 ID 参数(使用 GET 请求)到vote.phpdelete.php页面。这是 PHP 代码如何知道用户在表格中单击了哪个投票的方式。

提示:要在 PHP 中创建自定义 GET 请求,您可以将参数附加到 URL 中的 PHP 文件,例如:contact.php?name=david&email=david@codeshack.io.

如果我们导航到http://localhost/phppoll/index.php,我们应该看到以下内容:

http://localhost/phppoll/index.php

4e69a5eef4689538c96ee488d00deeed.png

我们现在可以查看在索引页面上创建的投票列表。不要担心按钮不起作用,因为我们尚未创建与它们关联的页面。

4.3. 创建页面

创建页面我们可以使用 HTML 表单和输入字段来创建新的投票,在服务器端,我们可以使用 PHP 和 MySQL 将新记录插入到我们的数据库表中,但是,要做到这一点,我们首先需要使用 PHP 执行 POST 请求。

编辑create.php文件并添加:

  1. <?php
  2. include 'functions.php';
  3. $pdo = pdo_connect_mysql();
  4. $msg = '';

我们将需要使用 MySQL 并使用我们之前创建的模板函数。因此,我们必须包含functions.php文件。这$味精变量将是给用户的输出消息。

之后添加:

  1. // Check if POST data is not empty
  2. if (!empty($_POST)) {
  3. // Post data not empty insert a new record
  4. // Check if POST variable "title" exists, if not default the value to blank, basically the same for all variables
  5. $title = isset($_POST['title']) ? $_POST['title'] : '';
  6. $description = isset($_POST['description']) ? $_POST['description'] : '';
  7. // Insert new record into the "polls" table
  8. $stmt = $pdo->prepare('INSERT INTO polls (title, description) VALUES (?, ?)');
  9. $stmt->execute([ $title, $description ]);
  10. // Below will get the last insert ID, this will be the poll id
  11. $poll_id = $pdo->lastInsertId();
  12. // Get the answers and convert the multiline string to an array, so we can add each answer to the "poll_answers" table
  13. $answers = isset($_POST['answers']) ? explode(PHP_EOL, $_POST['answers']) : '';
  14. foreach($answers as $answer) {
  15. // If the answer is empty there is no need to insert
  16. if (empty($answer)) continue;
  17. // Add answer to the "poll_answers" table
  18. $stmt = $pdo->prepare('INSERT INTO poll_answers (poll_id, title) VALUES (?, ?)');
  19. $stmt->execute([ $poll_id, $answer ]);
  20. }
  21. // Output message
  22. $msg = 'Created Successfully!';
  23. }
  24. ?>

上面的代码只有在用户点击 HTML 表单中的提交按钮时才会执行,因为它是一个 POST 请求。如果 POST 变量不为空,则在pollspoll_answers表中插入一条新记录——插入poll_answers表中的记录数取决于用户指定的答案数。

我们不仅可以插入新记录,而且还可以保护用户输入,因为准备好的语句将防止 SQL 注入。如果我们使用准备好的语句,我们不需要转义用户输入。

添加之后:

  1. <?=template_header('Create Poll')?>
  2. <div class="content update">
  3. <h2>Create Poll</h2>
  4. <form action="create.php" method="post">
  5. <label for="title">Title</label>
  6. <input type="text" name="title" id="title" placeholder="Title" required>
  7. <label for="description">Description</label>
  8. <input type="text" name="description" id="description" placeholder="Description">
  9. <label for="answers">Answers (per line)</label>
  10. <textarea name="answers" id="answers" placeholder="Description" required></textarea>
  11. <input type="submit" value="Create">
  12. </form>
  13. <?php if ($msg): ?>
  14. <p><?=$msg?></p>
  15. <?php endif; ?>
  16. </div>
  17. <?=template_footer()?>

还记得我们之前创建的索引模板吗?我们在技术上使用相同的页眉和页脚函数来构建我们的 HTML 模板。

我们在上面创建的表单可以用来将新记录插入到我们的数据库表中。PHP POST 变量名称反映了 HTML 表单中元素的名称。forms 方法设置为 post,因为我们需要发出 POST 请求。

现在,如果我们单击索引页面上的Create Poll按钮,我们将看到以下内容:

http://localhost/phppoll/create.php

b90a5a62a5e478568704d1d197d38904.png

这就是我们在数据库表中插入新记录所需要做的一切。

4.4. 投票页面

在投票页面上,用户将能够看到指定投票的填充答案列表,并可以选择投票。他们也可以在不投票的情况下看到结果。

编辑vote.php文件并添加:

  1. <?php
  2. include 'functions.php';
  3. // Connect to MySQL
  4. $pdo = pdo_connect_mysql();
  5. // If the GET request "id" exists (poll id)...
  6. if (isset($_GET['id'])) {
  7. // MySQL query that selects the poll records by the GET request "id"
  8. $stmt = $pdo->prepare('SELECT * FROM polls WHERE id = ?');
  9. $stmt->execute([ $_GET['id'] ]);
  10. // Fetch the record
  11. $poll = $stmt->fetch(PDO::FETCH_ASSOC);
  12. // Check if the poll record exists with the id specified
  13. if ($poll) {
  14. // MySQL query that selects all the poll answers
  15. $stmt = $pdo->prepare('SELECT * FROM poll_answers WHERE poll_id = ?');
  16. $stmt->execute([ $_GET['id'] ]);
  17. // Fetch all the poll anwsers
  18. $poll_answers = $stmt->fetchAll(PDO::FETCH_ASSOC);
  19. // If the user clicked the "Vote" button...
  20. if (isset($_POST['poll_answer'])) {
  21. // Update and increase the vote for the answer the user voted for
  22. $stmt = $pdo->prepare('UPDATE poll_answers SET votes = votes + 1 WHERE id = ?');
  23. $stmt->execute([ $_POST['poll_answer'] ]);
  24. // Redirect user to the result page
  25. header('Location: result.php?id=' . $_GET['id']);
  26. exit;
  27. }
  28. } else {
  29. exit('Poll with that ID does not exist.');
  30. }
  31. } else {
  32. exit('No poll ID specified.');
  33. }
  34. ?>

为了使投票页面正常工作,ID参数必须在 URL 中指定(vote.php?id=2 等)。如果ID参数存在,我们可以通过ID列(投票表)和poll_id列(poll_answers 表)。

我们不仅发出 GET 请求,而且还发出 POST 请求——只有当用户选择一个答案并单击“投票”按钮时,这将随后更新该特定答案的投票(MySQL UPDATE 查询)。在成功的 POST 请求后,用户将被重定向到结果页面 (result.php)。

之后添加:

  1. <?=template_header('Poll Vote')?>
  2. <div class="content poll-vote">
  3. <h2><?=$poll['title']?></h2>
  4. <p><?=$poll['description']?></p>
  5. <form action="vote.php?id=<?=$_GET['id']?>" method="post">
  6. <?php for ($i = 0; $i < count($poll_answers); $i++): ?>
  7. <label>
  8. <input type="radio" name="poll_answer" value="<?=$poll_answers[$i]['id']?>"<?=$i == 0 ? ' checked' : ''?>>
  9. <?=$poll_answers[$i]['title']?>
  10. </label>
  11. <?php endfor; ?>
  12. <div>
  13. <input type="submit" value="Vote">
  14. <a href="result.php?id=<?=$poll['id']?>">View Result</a>
  15. </div>
  16. </form>
  17. </div>
  18. <?=template_footer()?>

上面的模板将迭代每个答案并填充我们 HTML 表单所需的输入单选字段。

如果我们单击索引页面上测试投票旁边的眼睛图标,我们将看到以下内容:

http://localhost/phppoll/vote.php?id=1

ed5dde3dfa4f33acb1cc8949f484cf74.png

我们现在可以对我们创建的民意调查进行投票。

4.5. 结果页面

在结果页面上,用户可以查看填充的答案列表以及投票数。

编辑result.php文件并添加:

  1. <?php
  2. include 'functions.php';
  3. // Connect to MySQL
  4. $pdo = pdo_connect_mysql();
  5. // If the GET request "id" exists (poll id)...
  6. if (isset($_GET['id'])) {
  7. // MySQL query that selects the poll records by the GET request "id"
  8. $stmt = $pdo->prepare('SELECT * FROM polls WHERE id = ?');
  9. $stmt->execute([ $_GET['id'] ]);
  10. // Fetch the record
  11. $poll = $stmt->fetch(PDO::FETCH_ASSOC);
  12. // Check if the poll record exists with the id specified
  13. if ($poll) {
  14. // MySQL Query that will get all the answers from the "poll_answers" table ordered by the number of votes (descending)
  15. $stmt = $pdo->prepare('SELECT * FROM poll_answers WHERE poll_id = ? ORDER BY votes DESC');
  16. $stmt->execute([ $_GET['id'] ]);
  17. // Fetch all poll answers
  18. $poll_answers = $stmt->fetchAll(PDO::FETCH_ASSOC);
  19. // Total number of votes, will be used to calculate the percentage
  20. $total_votes = 0;
  21. foreach($poll_answers as $poll_answer) {
  22. // Every poll answers votes will be added to total votes
  23. $total_votes += $poll_answer['votes'];
  24. }
  25. } else {
  26. exit('Poll with that ID does not exist.');
  27. }
  28. } else {
  29. exit('No poll ID specified.');
  30. }
  31. ?>

与投票页面类似,我们需要检索 ID GET 参数(result.php?id=2 等),然后我们可以从数据库中检索投票结果——按投票数排序(降序)。使用 foreach 循环迭代答案,并相应地计算总票数。

之后添加:

  1. <?=template_header('Poll Results')?>
  2. <div class="content poll-result">
  3. <h2><?=$poll['title']?></h2>
  4. <p><?=$poll['description']?></p>
  5. <div class="wrapper">
  6. <?php foreach ($poll_answers as $poll_answer): ?>
  7. <div class="poll-question">
  8. <p><?=$poll_answer['title']?> <span>(<?=$poll_answer['votes']?> Votes)</span></p>
  9. <div class="result-bar" style= "width:<?=@round(($poll_answer['votes']/$total_votes)*100)?>%">
  10. <?=@round(($poll_answer['votes']/$total_votes)*100)?>%
  11. </div>
  12. </div>
  13. <?php endforeach; ?>
  14. </div>
  15. </div>
  16. <?=template_footer()?>

上面的模板将迭代答案并以 HTML 格式填充它们以及投票数和百分比条。

导航到测试投票,您可以单击投票或单击查看结果按钮,随后您应该会看到如下内容:

http://localhost/

37f684565fc18485bf199923ff4031b8.png

这基本上就是你如何填充投票结果并使用一些 CSS 魔法来创建百分比栏。

4.6. 删除页面

在删除页面上,我们将能够删除投票——我们将包含一个确认信息,这样用户就不会意外删除错误的投票。

编辑delete.php文件并添加:

  1. <?php
  2. include 'functions.php';
  3. $pdo = pdo_connect_mysql();
  4. $msg = '';
  5. // Check that the poll ID exists
  6. if (isset($_GET['id'])) {
  7. // Select the record that is going to be deleted
  8. $stmt = $pdo->prepare('SELECT * FROM polls WHERE id = ?');
  9. $stmt->execute([ $_GET['id'] ]);
  10. $poll = $stmt->fetch(PDO::FETCH_ASSOC);
  11. if (!$poll) {
  12. exit('Poll doesn\'t exist with that ID!');
  13. }
  14. // Make sure the user confirms beore deletion
  15. if (isset($_GET['confirm'])) {
  16. if ($_GET['confirm'] == 'yes') {
  17. // User clicked the "Yes" button, delete record
  18. $stmt = $pdo->prepare('DELETE FROM polls WHERE id = ?');
  19. $stmt->execute([ $_GET['id'] ]);
  20. // We also need to delete the answers for that poll
  21. $stmt = $pdo->prepare('DELETE FROM poll_answers WHERE poll_id = ?');
  22. $stmt->execute([ $_GET['id'] ]);
  23. // Output msg
  24. $msg = 'You have deleted the poll!';
  25. } else {
  26. // User clicked the "No" button, redirect them back to the home/index page
  27. header('Location: index.php');
  28. exit;
  29. }
  30. }
  31. } else {
  32. exit('No ID specified!');
  33. }
  34. ?>

如果投票 ID 已指定且存在于我们的投票表中,我们可以提示用户是否要删除投票。如果他们选择Yes,投票将与投票答案一起被永久删除。将使用 DELETE 语句从pollspoll_answers数据库表中删除数据。

之后添加:

  1. <?=template_header('Delete')?>
  2. <div class="content delete">
  3. <h2>Delete Poll #<?=$poll['id']?></h2>
  4. <?php if ($msg): ?>
  5. <p><?=$msg?></p>
  6. <?php else: ?>
  7. <p>Are you sure you want to delete poll #<?=$poll['id']?>?</p>
  8. <div class="yesno">
  9. <a href="delete.php?id=<?=$poll['id']?>&confirm=yes">Yes</a>
  10. <a href="delete.php?id=<?=$poll['id']?>&confirm=no">No</a>
  11. </div>
  12. <?php endif; ?>
  13. </div>
  14. <?=template_footer()?>

上面的代码是删除页面的模板。如果我们导航到索引页面并单击我们的一项民意调查旁边的垃圾桶图标,我们将看到如下内容:

http://localhost/phppoll/delete.php?id=1

021fdaa243d8374ca8fdd19cb74fe8e6.png

结论

恭喜!您现在已经成功地使用 PHP 和 MySQL 创建了一个投票和投票系统。

接下来是什么?考虑实施一种身份验证功能,限制某些用户创建和删除投票,或为投票和投票系统实施您自己的功能。

如果您喜欢这篇文章,请考虑在社交媒体网站上分享它,因为我们收到的访问者越多,我们可以创建的内容就越多。

发表评论

表情:
评论列表 (有 0 条评论,239人围观)

还没有评论,来说两句吧...

相关阅读

    相关 javaweb 投票系统

    最近做了一个简单的投票系统,来分享一下 1 先来看一下目录 ![在这里插入图片描述][20191023170720554.png] 2 效果图是这样的 首页,对

    相关 投票

    在许多选举的问题上,并不是每个人都是一张票的,很多时候会由于每个人的权利不同导致每个人的话事权也不一样(可认为所拥有的票数)假设有选举人V1,V2...Vk,他们所拥有的票数分

    相关 投票管理系统

    本次做的课设是投票管理系统,主要要求如下: ![这里写图片描述][SouthEast] 本次作业用到的是java-gui,可以说现在很少有小伙伴在用了吧。(-。-)