PHP 项目:创建一个投票应用程序

在这个 PHP 项目,我们将创建一个投票应用程序。

投票应用程序将由 3 个主要部分组成;

前端控制器 – 这是将确定要加载的 HTML 代码的索引页面。这将确保我们的应用程序有一个入口点。这将使我们对应用程序有更多的控制权。

业务逻辑 – 这将包含与数据库交互的 PHP 代码。这将使我们能够将业务逻辑与表示分离,使我们的应用程序易于维护

视图 – 这将包含 HTML 代码。我们将有两个页面,即:

  • opinion.html.php – 这将包含带有问题和选项的 HTML 代码
  • results.html.php – 这将包含显示投票结果的 HTML 代码

假设

投票将问这个问题 –

您最喜欢的 JavaScript 库是什么?

答案将是

  • JQuery
  • MooTools
  • YUI 库
  • Glow

以下是创建应用程序的步骤——

第一步)数据库连接

本节假设您了解 MySQL 及其管理方式,如果您不熟悉这些 MySQL,请查看我们的 SQL 教程部分。

我们的应用程序将只有一个表,包含 3 个字段,即:

  • id – 自动生成的数字作为主键
  • choice – 代表总统候选人的数字
  • ts – 投票的时间戳

以下脚本创建我们的 js_libraries 表。

<?php
CREATE TABLE `js_libraries` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `choice` tinyint(4) NOT NULL DEFAULT '0',

  `ts` timestamp NULL DEFAULT NULL,

  PRIMARY KEY (`id`)

);
?>

第二步)编码我们的应用程序

现在让我们创建将处理数据库连接的业务逻辑层。‘opinion_poll_model.php’

<?php

class Opinion_poll_model {

 private $db_handle; private $host = 'localhost'; private $db = 'opinion_poll';private $uid = 'root'; private $pwd = 'melody';

    public function __construct() {

        $this->db_handle = mysqli_connect($this->host, $this->uid, $this->pwd); //connect to MySQL server

        if (!$this->db_handle) die("Unable to connect to MySQL: " . mysqli_error());

        if (!mysqli_select_db($this->db_handle,$this->db)) die("Unable to select database: " . mysqli_error());

    }

    private function execute_query($sql_stmt) {

        $result = mysqli_query($db_handle,$sql_stmt); //execute SQL statement

        return !$result ? FALSE : TRUE;

    }

    public function select($sql_stmt) {

        $result = mysqli_query($db_handle,$sql_stmt);

        if (!$result) die("Database access failed: " . mysqli_error());

        $rows = mysqli_num_rows($result);

        $data = array();

        if ($rows) {

            while ($row = mysqli_fetch_array($result)) {

                $data = $row;

            }

        }

        return $data;

    }
    public function insert($sql_stmt) {

        return $this->execute_query($sql_stmt);

    }

    public function __destruct(){

        mysqli_close($this->db_handle);

    }

}

?>

此处,

  • “public function __construct()” 是类构造函数方法,用于建立数据库连接
  • “public function execute_query(…)” 是用于执行插入、更新和删除等查询的方法
  • “public function select” 是用于从数据库检索数据并返回数字数组的方法。
  • “public function insert(…)” 是调用 execute_query 方法的插入方法。
  • “public function __destruct()” 是用于关闭数据库连接的类析构函数。

现在让我们创建前端控制器 index.php

<?php

require 'opinion_poll_model.php';

$model = new Opinion_poll_model();

if (count($_POST) == 1) {

    echo "<script>alert('You did not vote!');</script>";

}

if (count($_POST) > 1) {

    $ts = date("Y-m-d H:i:s");

    $option = $_POST['vote'][0];

    $sql_stmt = "INSERT INTO js_libraries (`choice`,`ts`) VALUES ($option,'$ts')";

    $model->insert($sql_stmt);

    $sql_stmt = "SELECT COUNT(choice) choices_count FROM js_libraries;";

    $choices_count = $model->select($sql_stmt);

    $libraries = array("", "JQuery", "MooTools", "YUI Library", "Glow");

    $table_rows = '';

    for ($i = 1; $i < 5; $i++) {

        $sql_stmt = "SELECT COUNT(choice) choices_count FROM js_libraries WHERE choice = $i;";

        $result = $model->select($sql_stmt);

        $table_rows .= "<tr><td>" . $ libraries [$i] . " Got:</td><td><b>" . $result[0] . "</b> votes</td></tr>";

    }

    require 'results.html.php';

    exit;

}

require 'opinion.html.php';

?>

此处,

  • “require ‘opinion_poll_model.php’;” 加载业务逻辑类
  • “$model = new Opinion_poll_model();” 创建业务逻辑类的实例
  • “if (count($_POST) == 1)…” 执行数据验证,如果未投票给任何候选人,则使用 JavaScript 显示消息框。
  • “if (count($_POST) > 1)…” 通过计算 $_POST 数组中的项目数量来检查是否选择了投票。如果未选择任何项目,$_POST 将只包含 submit 项。如果选择了候选人,$_POST 数组将包含两个元素,即 submit 和 vote 项。此代码也用于插入新的投票记录,然后显示结果页面
  • “exit;” 用于在显示结果后终止脚本执行,以避免显示投票表单。
  • “require ‘opinion.html.php’;” 如果未选择任何内容,则显示投票表单。

现在让我们创建视图。opinion.html.php

<html>
    <head>
        <title>JavaScript Libraries - Opinion Poll</title>
    </head>
    <body>

        <h2>JavaScript Libraries - Opinion Poll</h2>

        <p><b>What is your favorite JavaScript?</b></p>

        <form method="POST" action="index.php">

            <p> <input type="radio" name="vote" value="1" />JQuery

                <br /><input type="radio" name="vote" value="2" />MooToolsl

                <br /><input type="radio" name="vote" value="3" />YUI Library

                <br /><input type="radio" name="vote" value="4" />Glow

            </p>

            <p><input type="submit" name="submitbutton" value="OK" /></p>

        </form>

    </body>

</html>

results.html.php

<html>

    <head>

        <title>JavaScript Libraries Poll Results</title>

    </head>

    <body>

        <h2>Opinion Poll Results</h2>

        <p><b>What is your favorite JavaScript Library?</b></p>

        <p><b><?php echo $choices_count[0]; ?></b> people have thus far taken part in this poll:</p>

        <p>
<table>

            <?php echo($table_rows); ?>
        </table>
</body>
</html>

第三步)测试我们的应用程序

假设您已将文件保存在 opinionpoll 文件夹中,请浏览到 URL https:///opinionpoll/

Testing an Opinion Poll Application

如果您在未选择 JS 库的情况下单击“确定”按钮,您将看到以下消息框。

Testing an Opinion Poll Application

选择一个 JS 库,然后单击“确定”按钮。您将看到与下面类似的“结果”页面。

Testing an Opinion Poll Application

摘要

  • 将应用程序划分为业务逻辑、前端控制器和视图层是良好的应用程序设计实践
  • JavaScript 对于执行客户端验证非常有用
  • 使用 file.html.php 作为包含 HTML 和 PHP 代码的文件是良好的编程实践
  • 投票应用程序演示了如何将先前课程中学到的知识结合起来,开发一个具有数据库后端的实际应用程序。