1.建立两个表格:要显示百分比的话,就要在选项表中加上一列标记number
2.链接数据库,并对题目和选项进行显示
<?php
$db=new MySQLi("localhost","root","123","test1");
mysqli_connect_error()?"连接失败":"";
$sql1="select * from timu ";
$result1=$db->query($sql1);
$attr1=$result1->fetch_row(); $sql2="select * from xuanxiang";
$result2=$db->query($sql2);
$attr2=$result2->fetch_all();
?>
<div id="timu" style="display:block;">
<form action="toupiao.php" method="post">
<?php
echo $attr1[1];//题目显示
$v=array();
foreach($attr2 as $v)
{
echo "<div><input type='checkbox' value='{$v[0]}' name='xx[]'>{$v[1]}</div>"; //选项显示
} ?>
<input type="submit" value="投票"><input type="button" value="查看详情" onclick="xianshi(0)">
</form> </div> <div id='baifenbi' style="display:none;">
<?php
3.给选中项的number列加1处理
/*--------------------------选中的数量加1--------计算number列的总数量----------------------------------------*/
if(!empty($_POST['xx']))
{
$attr3=$_POST['xx'];
$str=implode("','",$attr3);
$sql3="update xuanxiang set number=number+1 where ids in ('{$str}')"; //给number列+1,
$result3=$db->query($sql3);
if($result3)
{
$sql4="select sum(number) from xuanxiang";
$result4=$db->query($sql4);
$num=$result4->fetch_row(); //把number列的数值取总和
4.显示选项的百分比
/*------------------------------百分比显示---------------------------------------------------------*/
echo "<div>"; foreach($attr2 as $vv)
{
$baifenbi=($vv[2]/$num[0])*100; echo "{$vv[1]} {$baifenbi}%<div style='width:200px;height:6px; border:1px solid black;'><div style='width:{$baifenbi}%;height:6px;background-color:red;'></div></div>"; //显示百分比,是用两个div,外层的固定宽度,内层的通过百分比给宽度赋值,并设背景色 }
echo "<input type='button' value='返回' onclick='xianshi(1)'>";
echo "</div>";
}
} ?>
5.js实现投票和百分比显示的交替(投票和百分比界面分别写在两个div中)
<script>
function xianshi(a)
{
if(a==0)
{
document.getElementById("baifenbi").style.display="block";
document.getElementById("timu").style.display="none";
}
else
{
document.getElementById("baifenbi").style.display="none";
document.getElementById("timu").style.display="block";
}
} </script>