Last active
November 1, 2016 00:54
-
-
Save cahsowan/cc1c7001f3660d5511c9bb62c95f6df0 to your computer and use it in GitHub Desktop.
Simple example of polling using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$pertanyaan = "Sistem operasi HP terbaik adalah?"; | |
$pilihan = [ | |
'android' => 'Android', | |
'ios' => 'iOS', | |
'wp' => 'Windows Phone' | |
]; | |
function getData(){ | |
$empty_counter = [ | |
'android' => 0, | |
'ios' => 0, | |
'wp' => 0 | |
]; | |
$result = json_decode(file_get_contents('data.txt'), true); | |
return is_null($result) ? $empty_counter : $result; | |
} | |
function writeData($data){ | |
file_put_contents('data.txt', json_encode($data)); | |
} | |
if ($_POST['pilihanmu']) { | |
$data = getData(); | |
$data[$_POST['pilihanmu']] +=1; | |
writeData($data); | |
$total = array_sum($data); | |
} | |
?> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Jajak Pendapat (POLLING)</title> | |
<style type="text/css"> | |
li { list-style: none; } | |
</style> | |
</head> | |
<body> | |
<h1>Jajak Pendapat</h1> | |
<hr> | |
<form method="POST" action="<?php echo $PHP_SELF ?>"> | |
<p><?php echo $pertanyaan ?></p> | |
<ul> | |
<?php foreach ($pilihan as $key => $os): ?> | |
<li> | |
<input type="radio" name="pilihanmu" value="<?php echo $key ?>"> <?php echo $os ?> | |
</li> | |
<?php endforeach ?> | |
</ul> | |
<button type="submit">Vote</button> | |
</form> | |
<?php if ($_POST['pilihanmu']): ?> | |
<hr> | |
<table border="1"> | |
<?php foreach ($data as $key => $value): ?> | |
<tr> | |
<td><?php echo $pilihan[$key] ?></td> | |
<td style="width:200px"> | |
<div style="background:red; height:10px; width: <?php echo $value / $total * 100 ?>%"></div> | |
</td> | |
<td><?php echo $value ?></td> | |
</tr> | |
<?php endforeach ?> | |
</table> | |
<?php endif ?> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment