---
description: In this PHP project, we are going to create an opinion poll application. The opinion poll will consist of 3 major components; Front controller, Business Logic, View.
title: PHP Projects: Create an Opinion Poll Application
image: https://www.guru99.com/images/case-study-opinion.png
---

 

[Skip to content](#main) 

In this PHP project**,** we are going to create an opinion poll application.

The opinion poll will consist of 3 major components;

**Front controller** – this is the index page that will determine the HTML code to be loaded. This will ensure that our application has a single entry point. This will give us more control over the application.

**Business Logic** – this will contain the PHP code for interacting with the database. This will allow us to separate the business logic from the presentation making our application easy to maintain

**Views** – this will contain the HTML code. We will have two pages namely;

* opinion.html.php – this will contain the HTML code with the question and options
* results.html.php – this will contain the HTML code that displays the opinion poll results

Assumptions made

The opinion poll will ask the question –

What is your favorite[ JavaScript ](https://www.guru99.com/interactive-javascript-tutorials.html)Library?

Answers would be

* JQuery
* MooTools
* YUI Library
* Glow

Here are the steps to create the application–

## Step 1) Database Connectivity

This section assumes knowledge of MySQL and how to administer it, if you are not familiar with these MySQL, check our [SQL tutorials](https://www.guru99.com/sql.html) section.

Our application will have one table only with 3 fields namely;

* id – auto-generate number as the primary key
* choice – the number representing a presidential candidate
* ts – the timestamp for the vote

The script below creates our js\_libraries table.

<?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`)

);
?>

## Step 2) Coding our application

Let’s now create our business logic layer that will handle the database connectivity. _‘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);

    }

}

?>

HERE,

* “public function \_\_construct()” is the class constructor method that is used to establish the database connection
* “public function execute\_query(…)” is the method for executing queries such as insert, update and delete
* “public function select” is the method for retrieving data from the [database](https://www.guru99.com/introduction-to-database-sql.html) and returning a numeric array.
* “public function insert(…)” is the insert method that calls the execute\_query method.
* “public function \_\_destruct()” is the class destructor that closes the database connection.

Let’s now create the front controller _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';

?>

HERE,

* “require ‘opinion\_poll\_model.php’;” loads the business logic class
* “$model = new Opinion\_poll\_model();” creates an instance of the business logic class
* “if (count($\_POST) == 1)…” performs the data validation and uses JavaScript to display a message box if not candidate has been voted for.
* “if (count($\_POST) > 1)…” checks if a vote has been selected by counting the number of items in the $\_POST array. If no item has been select, the $\_POST will only contain the submit item. If a candidate has been chosen, the $\_POST array will two elements, the submit and vote item. This code is also used to insert a new vote record and then display the results page
* “exit;” is used to terminate the script execution after the results have been displayed so that the opinion poll form is not displayed.
* “require ‘opinion.html.php’;” displays the opinion poll form if nothing has been selected.

Let’s now create the views. _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>

## Step 3) Testing our application

Assuming you have saved the files in opinionpoll folder, browse to the URL http://localhost/opinionpoll/

[![Testing an Opinion Poll Application](https://www.guru99.com/images/2013/04/opinion_poll_home.jpg)](https://www.guru99.com/images/2013/04/opinion%5Fpoll%5Fhome.jpg)

If you click on the Ok button without selecting a JS library, you will get the following message box.

[![Testing an Opinion Poll Application](https://www.guru99.com/images/2013/04/validation_msg.jpg)](https://www.guru99.com/images/2013/04/validation%5Fmsg.jpg)

Select a JS library then click on OK button. You will get the results page similar to the one shown below.

[![Testing an Opinion Poll Application](https://www.guru99.com/images/2013/04/opinion_poll_results.jpg)](https://www.guru99.com/images/2013/04/opinion%5Fpoll%5Fresults.jpg)

## Summary

* Dividing your application into business logic, front controller view layers is a good application design practice
* JavaScript is useful for performing client-side validation
* It is a good programming practice to use file.html.php for files that contain both HTML and [PHP codes](https://www.guru99.com/php-tutorials.html)
* The opinion poll application demonstrates how the knowledge learned in the previous lessons can be put together to developing a working application with a database back end.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter](https://www.guru99.com/images/footer-email-avatar-imges-1.png) Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/case-study-opinion.png","url":"https://www.guru99.com/images/case-study-opinion.png","width":"425","height":"315","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/case-study-opinion-poll-app.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/php","name":"PHP"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/case-study-opinion-poll-app.html","name":"PHP Projects: Create an Opinion Poll Application"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/case-study-opinion-poll-app.html#webpage","url":"https://www.guru99.com/case-study-opinion-poll-app.html","name":"PHP Projects: Create an Opinion Poll Application","dateModified":"2024-06-28T14:59:59+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/case-study-opinion.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/case-study-opinion-poll-app.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/fiona","name":"Fiona Brown","description":"I'm Fiona brown, a Full Stack Developer with over a decade of experience, sharing practical guides on robust and scalable application development.","url":"https://www.guru99.com/author/fiona","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/fiona-brown-author.png","url":"https://www.guru99.com/images/fiona-brown-author.png","caption":"Fiona Brown","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"@type":"NewsArticle","headline":"PHP Projects: Create an Opinion Poll Application","keywords":"php","dateModified":"2024-06-28T14:59:59+05:30","articleSection":"PHP","author":{"@id":"https://www.guru99.com/author/fiona","name":"Fiona Brown"},"publisher":{"@id":"https://www.guru99.com/#organization"},"description":"In this PHP project, we are going to create an opinion poll application. The opinion poll will consist of 3 major components; Front controller, Business Logic, View.","copyrightYear":"2024","copyrightHolder":{"@id":"https://www.guru99.com/#organization"},"name":"PHP Projects: Create an Opinion Poll Application","@id":"https://www.guru99.com/case-study-opinion-poll-app.html#richSnippet","isPartOf":{"@id":"https://www.guru99.com/case-study-opinion-poll-app.html#webpage"},"image":{"@id":"https://www.guru99.com/images/case-study-opinion.png"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/case-study-opinion-poll-app.html#webpage"}}]}
```
