Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/ee67410fde7011c7c2fcecd7c9e56231 to your computer and use it in GitHub Desktop.
Save code-boxx/ee67410fde7011c7c2fcecd7c9e56231 to your computer and use it in GitHub Desktop.
PHP MYSQL Polling/Voting System

SIMPLE PHP MYSQL POLL/VOTE SYSTEM

https://code-boxx.com/simple-php-poll-mysql/

NOTES

  1. Create a database and import 1-database.sql.
  2. Change the database settings in 2-lib-poll.php to your own.
  3. Launch 3-poll.php in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) POLL QUESTIONS
CREATE TABLE `poll_questions` (
`poll_id` bigint(20) NOT NULL,
`poll_question` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `poll_questions`
ADD PRIMARY KEY (`poll_id`);
ALTER TABLE `poll_questions`
MODIFY `poll_id` bigint(20) NOT NULL AUTO_INCREMENT;
-- (B) POLL OPTIONS
CREATE TABLE `poll_options` (
`poll_id` bigint(20) NOT NULL,
`option_id` bigint(20) NOT NULL,
`option_text` varchar(255) NOT NULL,
`option_votes` bigint(20) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `poll_options`
ADD PRIMARY KEY (`poll_id`,`option_id`);
-- (C) DUMMY DATA
INSERT INTO `poll_questions` (`poll_id`, `poll_question`) VALUES
(1, 'What is your favorite meme animal?');
INSERT INTO `poll_options` (`poll_id`, `option_id`, `option_text`, `option_votes`) VALUES
(1, 1, 'Doge', 99),
(1, 2, 'Cate', 88),
(1, 3, 'Birb', 77);
<?php
class Poll {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $error = "";
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt!==null) { $this->stmt = null; }
if ($this->pdo!==null) { $this->pdo = null; }
}
// (C) EXECUTE SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET POLL & VOTES
function get ($pid) {
// (D1) GET POLL QUESTION
$this->query("SELECT `poll_question` FROM `poll_questions` WHERE `poll_id`=?", [$pid]);
$question = $this->stmt->fetchColumn();
if ($question == false) { return false; }
// (D2) GET POLL OPTIONS & VOTES
$this->query("SELECT * FROM `poll_options` WHERE `poll_id`=?", [$pid]);
$options = [];
while ($row = $this->stmt->fetch()) {
$options[$row["option_id"]] = [
"t" => $row["option_text"],
"v" => $row["option_votes"]
];
}
// (D3) RESULT
return ["q"=>$question, "o"=>$options];
}
// (E) SAVE VOTE
function save ($pid, $up=null, $down=null) {
// (E1) GET CURRENT VOTES
$votes = $this->get($pid);
if ($votes==false) {
$this->error = "Invalid poll";
return false;
}
// (E2) UPDATE VOTES
$sql = "UPDATE `poll_options` SET `option_votes`=? WHERE `poll_id`=? AND `option_id`=?";
if (is_numeric($up)) {
$this->query($sql, [$votes["o"][$up]["v"]+1, $pid, $up]);
}
if (is_numeric($down)) {
$this->query($sql, [$votes["o"][$down]["v"]-1, $pid, $down]);
}
return true;
}
}
// (F) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (G) START SESSION & NEW POLL OBJECT
session_start();
$POLL = new Poll();
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
.poll-docket {
max-width: 400px;
padding: 20px;
border-radius: 10px;
background: #eee;
}
.poll-question {
font-size: 20px;
font-weight: 700;
}
.poll-option {
display: block;
width: 100%;
padding: 10px 0;
}
.poll-go {
width: 100%;
background: #981818;
color: #fff;
padding: 10px;
border: 0;
font-size: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>POLL DEMO</title>
<meta charset="utf-8">
<link rel="stylesheet" href="3-poll.css">
</head>
<body>
<?php
// (A) INIT
$pid = 1; // fixed to poll id 1 for this demo
require "2-lib-poll.php"; // load poll library
if (!isset($_SESSION["poll"])) { $_SESSION["poll"] = []; } // to track user vote
if (!isset($_SESSION["poll"][$pid])) { $_SESSION["poll"][$pid] = null; }
// (B) UPDATE POLL VOTE
if (count($_POST)!=0) { if ($_POST["vote"] != $_SESSION["poll"][$pid]) {
$up = $_POST["vote"];
$down = $_SESSION["poll"][$pid]!=$up ? $_SESSION["poll"][$pid] : null ;
if ($POLL->save($pid, $up, $down)===false) { echo $POLL->error; }
$_SESSION["poll"][$pid] = $up;
}}
// (C) GET & SHOW THE POLL
$poll = $POLL->get($pid); ?>
<form method="post" class="poll-docket">
<div class="poll-question"><?=$poll["q"]?></div>
<?php foreach ($poll["o"] as $oid=>$o) { ?>
<label class="poll-option">
<input type="radio" name="vote" value="<?=$oid?>"
<?=$oid==$_SESSION["poll"][$pid]?" checked":""?>>
<span class="poll-text"><?=$o["t"]?></span>
<span class="poll-votes">(<?=$o["v"]?>)</span>
</label>
<?php } ?>
<input type="submit" class="poll-go" value="Go!">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment