Object-oriented programming is used to design, develop and implement many simple as well as complex applications. We have already seen object-oriented features of PHP in a previous tutorial. Let us use object-oriented programming to create PHP poll system.
I have created a poll system to let the user vote for their favorite courses. The user will choose their favorite course by using the HTML form radio options. On submitting the selected course, the PHP code will call model class functions to perform poll actions.
I used two classes Poll.php and Dao.php in this PHP poll example. The Poll.php model class contains functions to add a new vote entry to the database and get courses with the existing vote count.
In Dao.php class I have dealt with the database access functions to perform create and read operations.
The first screenshot displays the HTML form radio options with the courses from the database. After submitting the poll options, the vote count will be displayed for each course as shown in the second screenshot.
The favourite courses are stored in the tbl_courses table. The course id is mapped in the tbl_course_vote table with the one-to-many relationship.
Run the SQL script shown below to create required database table structure and the data. Otherwise, you can import the SQL file I have added to the code download at the end of this post.
CREATE TABLE `tbl_course` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `tbl_course` (`id`, `name`, `date`) VALUES
(1, 'Artificial Intelligence', '2018-03-27 08:53:59'),
(2, 'Network Security', '2018-03-27 08:54:27'),
(3, 'Information Retrieval', '2018-03-27 08:54:54'),
(4, 'Global Positioning System', '2018-03-27 08:56:53');
----------------------------------------------------------
CREATE TABLE `tbl_course_vote` (
`id` int(11) NOT NULL,
`course_id` int(20) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This HTML form shows the list of courses from the database with the radio options. The user can select their favourite course using this radio options.
On submitting the selected course, PHP code will perform the poll action by calling the model class functions. After processing the poll data, I show the number of votes added for each course.
<div class="poll-container">
<?php
if (empty($_POST["submit"])) {
$result = $pollObject->getCource();
?>
<form method="POST" action="">
<?php
foreach ($result as $k => $v) {
?>
<div class='option-row'>
<input class='radio-input' type='radio' name='vote'
value='<?php echo $result[$k]["id"]; ?>' />
<?php echo $result[$k]["name"]; ?>
</div>
<?php } ?>
<input id="btnSubmit" type="submit" name="submit" value="Submit" />
</form>
<div></div>
<?php
} else {
$pollObject->addVote($subjectId);
$result = $pollObject->getCourcewithVote();
foreach ($result as $k => $v) {
?>
<div class='poll'>
<?php echo $result[$k]["name"]; ?>
<b>
<?php echo $result[$k]["vote_count"]; ?>
</b> votes
</div>
<?php
}
}
?>
</div>
This class includes functions to add new vote entry and to get the courses and their existing vote count from the database. On submitting the poll data, the Poll class object will be created to invoke its function addVote().
In this function, the insert query is created by using the poll data submitted by the user.
<?php
require_once 'Dao.php';
class Poll{
public function addVote($subjectOption)
{
$daoObject = new Dao();
$sql = "INSERT INTO tbl_subject_vote (subject_id) VALUES ('".$subjectOption."')";
$daoObject->insert($sql);
}
public function getCource()
{
$daoObject = new Dao();
$sql = "SELECT * FROM tbl_course order by id";
$result = $daoObject->select($sql);
return $result;
}
public function getCourcewithVote()
{
$daoObject = new Dao();
$sql = "SELECT * FROM tbl_course order by id";
$result = $daoObject->select($sql);
if(!empty($result)) {
foreach ($result as $k => $v) {
$result[$k]["vote_count"] = 0;
$sql_stmt = "SELECT COUNT(course_id) as vote_count FROM tbl_course_vote WHERE course_id = ". $result[$k]["id"];
$voteResult = $daoObject->select($sql_stmt);
if(!empty($voteResult[0]["vote_count"])) {
$result[$k]["vote_count"] = $voteResult[0]["vote_count"];
}
}
}
return $result;
}
}
?>
In this class, the database related functions like create and read operations are performed. by using these functions the poll data will be updated in the database.
The database configurations are set as the properties of this class. The connection is established on the class constructor and closed on the destructor.
<?php
class Dao {
private $db_handle;
private $host = 'localhost';
private $database = 'phpsamples';
private $userid = 'root';
private $password = 'test';
public function __construct() {
$this->db_handle = mysqli_connect($this->host, $this->userid, $this->password, $this->database);
if (!$this->db_handle)
{
die("Connection not established: " . mysqli_error());
}
if (!mysqli_select_db($this->db_handle,$this->database))
{
die("Unable to select database: " . mysqli_error());
}
}
public function select($sql) {
$result = mysqli_query($this->db_handle,$sql);
if (!$result)
{
die("Unable to access database: " . mysqli_connect_error());
}
$rows = mysqli_num_rows($result);
$rowdata = array();
if ($rows)
{
while ($row = mysqli_fetch_assoc($result))
{
$rowdata[] = $row;
}
}
return $rowdata;
}
public function insert($sql)
{
$result = mysqli_query($this->db_handle,$sql);
return $result;
}
public function __destruct()
{
mysqli_close($this->db_handle);
}
}
?>