PHP学习笔记:php投票系统

 说明:代码来源《PHP和MySQL Web应用开发》一书,还有就是代码有些是经过修改的,经过我的测验全部都可以用。

   书中源码在IE中是可以用的,不过在谷歌出现一些问题就是复选框应用不了,一直提示没有选中。还有就是,中文编码问题

   //self.document.all.item("voteitem",j)在ie浏览器中可以用,但在谷歌等实现不了复选框的选择
        //这里我们改用这个代替:var nn = self.document.all.item("voteitem"); ————>nn[j].checked

 

本示例的数据库脚本 ~~~    MySQL执行语句:  source d:\test\Vote.sql;

 

CREATE DATABASE IF NOT EXISTS Vote
COLLATE 'gb2312_chinese_ci';

USE Vote;
CREATE TABLE IF NOT EXISTS VoteItem (
    Id  INT  AUTO_INCREMENT  PRIMARY KEY,
    Item VARCHAR(50), 
    VoteCount INT
    );

CREATE TABLE IF NOT EXISTS  VoteIP (
    IP  VARCHAR(50)  PRIMARY KEY
);

 

 

style.CSS  CSS样式代码

td {  font-family: "Courier","Ó×Ô²"; font-size: 9pt;line-height:14pt; color: #000080;letter-spacing:1pt}
div {font-family: "Courier","Ó×Ô²";font-size:9pt; color:#008080;letter-spacing:4;line-height:14pt}
span {font-family: "Courier","Ó×Ô²";font-size:9pt; color:#008080;letter-spacing:2;line-height:14pt}
p {  font-family:  "Courier","Ó×Ô²"; font-size:9pt; color: #B0DCF0;line-height:14pt}
.alert {  font-family:  "Courier","Ó×Ô²"; font-size:9pt; line-height:14pt; color: 008080;letter-spacing:2}
a:link {  font-family:  "Courier","Ó×Ô²"; font-size:9pt; color:#008080;  }
a:visited {  font-family:  "Courier","Ó×Ô²"; font-size:9pt; color:#999999;}
a:hover {  font-family:  "Courier","Ó×Ô²"; font-size:9pt; color: #FF0000; text-decoration: underline;}
INPUT.text,INPUT.file{FONT-SIZE: 9pt ;font-family: "Courier","Ó×Ô²";color:#000080;background-color:#ffffff;border:1 solid #B0DCF0}
INPUT.Submit {height=20;border:1 solid #B0DCF0;font-family: "Courier","Ó×Ô²";BACKGROUND-COLOR:#64B9E1; FONT-SIZE: 9pt ;font-color:#B0DCF0; PADDING-TOP: 1px}
View Code

 

Class文件包含2个文件 VoteIP.php(VoteIP类) 和 VoteItem.php(VoteItem类) 。

 

VoteIP.php(VoteIP类)

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″> 
<?PHP
    class VoteIP
    {
        var $conn;

        public $IP;        // IP地址    
                
        function __construct() {
            // 链接到数据库book,连接对象为$conn
            $this->conn = mysqli_connect("localhost", "root", "123456", "Vote"); 
            mysqli_query($this->conn, "SET NAMES utf-8");
        }
        
        function __destruct() {
            // 关闭$conn中保存的数据库连接
            mysqli_close($this->conn);
        }

        // 判断指定的IP地址是否存在,参数$_ip表示IP地址
        function exists($_ip)
        {
            $result = $this->conn->query("SELECT * FROM VoteIP WHERE IP='" . $_ip . "'");
            if($row = $result->fetch_row()) 
                return true;
            else
                return false;
        }
        
        // 将当前对象的成员变量数据保存到表Voteip中
        function insert()
        {
            $sql = "INSERT INTO VoteIP VALUES('" . $this->IP . "')";
            $this->conn->query($sql);
        }

        // 删除IP记录
        function deleteAll() {
            $sql = "DELETE FROM VoteIP";
            $this->conn->query($sql);
        }
    }
?>
View Code

 

VoteItem.php(VoteItem类)

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″> 
<?PHP
    class VoteItem
    {
        var $conn;

        public $Id;                // 项目ID,主键,自动编号
        public $Item;            // 项目名称
        public $VoteCount;        //投票数量,缺省为0
            
        function __construct() {
            // 链接到数据库book,连接对象为$conn
            $this->conn = mysqli_connect("localhost", "root", "123456", "vote"); 
            mysqli_query($this->conn, "SET NAMES utf-8");
        }
        
        function __destruct() {
            // 关闭$conn中保存的数据库连接
            mysqli_close($this->conn);
        }
        
        // 判断指定的项目名称是否存在,参数$title表示项目名称
        function exists($title)
        {            
            $sql = "SELECT * FROM VoteItem WHERE Item='" . $title . "'";
            $result = $this->conn->query($sql);
            if($row = $result->fetch_row())  
                Return true;
            else
                Return false;
        }

         //获取项目的内容,参数$Id表示项目编号
        function GetInfo($Id)
        {            
            $sql = "SELECT * FROM VoteItem WHERE Id=" . $Id;
            $result = $this->conn->query($sql);
            if($row = $result->fetch_row())  
            {
                $this->Id = $Id;
                $this->Item = $row[1];
                $this->VoteCount = (int)$row[2];
            }
        }
                
        //插入新记录
        function insert()
        {
            $sql = "INSERT INTO VoteItem (Item, VoteCount) VALUES('" . $this->Item . "', 0)";
            $this->conn->query($sql);
        }        
        

        //删除项目记录,参数$Id表示项目编号
        function delete($Ids)
        {
            $sql = "DELETE FROM VoteItem WHERE Id IN (" . $Ids . ")";
            $this->conn->query($sql);
        }            
        
        //修改项目记录
        function updateItem($newItem, $id) {
            $sql = "UPDATE VoteItem SET Item='" . $newItem . "' WHERE Id=" . $id;
            $this->conn->query($sql);
        }

        //删除项目记录
        function clearCount() {
            $sql = "UPDATE VoteItem Set VoteCount=0 WHERE Id>0";
            $this->conn->query($sql);            
        }

        //获取项目的投票数量
        function getItemCount() {
            $sql = "SELECT Count(*) FROM VoteItem";
            $results = $this->conn->query($sql);            
            if($row = $results->fetch_row())
                Return (int)$row[0];
            else
                Return 0;                
        }

        //获取全部项目的投票总数量
        function SumItemCount() {
            $sql = "SELECT Sum(VoteCount) FROM VoteItem";
            $results = $this->conn->query($sql);            
            if($row = $results->fetch_row())
                Return (int)$row[0];
            else
                Return 0;                
        }

        //将指定编号的项目投票数量加1
        function updateCount($Ids) {
            $sql = "UPDATE VoteItem SET VoteCount=VoteCount+1 WHERE Id IN (" . $Ids . ")";
            $this->conn->query($sql);
        }

        //选取全部记录显示
        function load_VoteItem()
        {
            $sql = "SELECT * FROM VoteItem";
            $results = $this->conn->query($sql);
            Return $results;
        }
    }
?>
View Code

 

AddItem.php   投票项目管理模块代码(系统管理员可以增加、修改和删除投票项目 ,还有设置重新投票)

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″> 
<title>投票项目</title>
<link rel="stylesheet" href="style.css">
</head>

<script language="JavaScript">
function newwin(url) {
  var oth="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,left=200,top=200";
  oth = oth+",width=200,height=100";
  var newwin=window.open(url,"newwin",oth);
  newwin.focus();
  return false;
}

function SelectChk()
{
    var s=false;
    var itemid,n=0;
    var strid,strurl;
    var nn = self.document.all.item("voteitem");
    for (j=0;j<nn.length-1;j++)
    {
        //if (self.document.all.item("voteitem",j).checked)
        //self.document.all.item("voteitem",j)在ie浏览器中可以用,但在谷歌等实现不了复选框的选择
        //这里我们改用这个代替:var nn = self.document.all.item("voteitem"); ————>nn[j].checked
        if (nn[j].checked)
        {
            n = n + 1;
            s=true;
            //itemid = self.document.all.item("voteitem",j).id+"";
            itemid = nn[j].id+"";
            if(n==1)
            {
                strid = itemid;
            }
            else
            {
                    strid = strid + "," + itemid;
            }        
        }
    }
    strurl = "AddItem.php?Oper=delete&id=" + strid;
    if(!s)    {
        alert("请选择要删除的投票项目!");
        return false;
    }
    
    if ( confirm("你确定要删除这些投票项目吗?")) {
        form1.action = strurl;
        form1.submit();
    }
}
function sltAll()
{
    var nn = self.document.all.item("voteitem");
    for(j=0;j<nn.length;j++)
    {
        //self.document.all.item("voteitem",j).checked = true;
        nn[j].checked = true;
    }
}
function sltNull()
{
    var nn = self.document.all.item("voteitem");
    for(j=0;j<nn.length;j++)
    {
        //self.document.all.item("voteitem",j).checked = false;
        nn[j].checked = false;
    }
}
</script>
<body link="#000080" vlink="#080080">
<form id="form1" name="form1" method="POST">
<?PHP
error_reporting(0);
    $Soperate = $_GET["Oper"];  // 操作标记
    include("Class\VoteItem.php");
    $obj = new VoteItem();    // 定义VoteItem类对象
    $Operid = $_GET["id"];    // 项目编号
    if($Soperate=="add") {     // 添加项目
        $newTitle = $_POST["txttitle"];
        echo($newTitle);
        // 判断数据库中是否存在此类别
        if($obj->exists($newTitle))
            echo("已经存在此投票项目,添加失败!");
        else {
            $obj->Item = $newTitle;
            $obj->insert();
            echo("投票项目已经成功添加!");
        }
    }
    elseif($Soperate == "edit")   { // 修改项目
        $newTitle = $_POST["txttitle"];
        $orgTitle = $_POST["sOrgTitle"];
        echo("newTitle : " . $newTitle . "  orgTitle: " . $orgTitle);
        // 如果新类别名称和旧的不同则执行
        if($newTitle<>$orgTitle)  {
            // 判断数据库中是否存在此类别
            if($obj->exists($newTitle)) 
                echo("已经存在此投票项目,添加失败!");
            else {
                $obj->updateItem($newTitle, $Operid);
                echo("投票项目已经成功修改!");
            }
        }
    }
    elseif($Soperate=="delete")  {      // 删除项目
        $obj->delete($Operid);
        echo("投票项目已经成功删除!");
    }
?>
<p align="center"><font style="FONT-SIZE: 12pt"><b>投 票 项 目 管 理</b></font></p>
<center>
<table border="1" cellspacing="0" width="60%"  bordercolorlight="#4DA6FF" bordercolordark="#ECF5FF" style="FONT-SIZE: 9pt">
  <tr>
    <td width="60%" align="center" bgcolor="#FEEC85"><strong>项 目</strong></td>
    <td width="20%" align="center" bgcolor="#FEEC85"><strong>修 改</strong></td>
    <td width="20%" align="center" bgcolor="#FEEC85"><strong>选 择</strong></td>
  </tr>
<?PHP

    $hasData = false;        // 记录$results中是否存在记录
    $results = $obj->load_VoteItem();
    while($row = $results->fetch_row())  { 
        $hasData = true;
?>
        <tr><td> <?PHP echo($row[1]);?> </td>
        <td align="center"><a href="AddItem.php?Oper=update&id=<?PHP echo($row[0]);?>&name=<?PHP echo($row[1]); ?>">修改</a></td>
        <td align="center"><input type="checkbox" name="voteitem" id=<?PHP echo($row[0]); ?>></td>  </tr>
<?PHP
    }
    
    if(!$hasData)  {
?>
        <tr><td colspan=3 align=center><font style="COLOR:Red">目前还没有投票项目。</font></td></tr></table>
<?PHP }  ?>
  
</table>
        <p align="center">
        <input type="button" name="revote" value=" 重新投票 " onclick="return newwin('ReVote.php')"> &nbsp;&nbsp;
<?PHP
    if($hasData)  {
?>
         <input type="button" value="全 选" onclick="sltAll()"> 
         &nbsp;&nbsp;<input type="button" value="清 空" onclick="sltNull()"> 
         &nbsp;&nbsp;<input type="submit" value="删 除" name="tijiao" onclick="SelectChk()"> 
<?PHP 
    }
?>
</form>
<?PHP
    // 如果为修改和添加操作,则分别显示下面的内容
    if($Soperate == "update")  {
        $sTitle = $_GET["name"];
?>
    <form name="UFrom" method="post" action="AddItem.php?id=<?PHP echo($Operid); ?>&Oper=edit">
      <div align="center">
        <input type="hidden" name="sOrgTitle" value="<?PHP echo($sTitle); ?>"><font color="#FFFFFF"><b><font color="#000000">投票项目名称</font></b></font> 
        <input type="text" name="txttitle" size="20" value="<?PHP echo($sTitle); ?>"> 
        <input type="submit" name="Submit" value=" 修 改 "> 
        </div>
    </form>
<?PHP
    }
    else {        
?>
    <form name="AForm" method="post" action="AddItem.php?Oper=add">
      <div align="center">
        <font color="#FFFFFF"><b><font color="#000000">投票项目名称</font></b></font> 
        <input type="text" name="txttitle" size="20"> 
        <input type="submit" name="Submit" value=" 添 加 "> 
      </div>
    </form>
<?PHP }  ?>
<input type="hidden" name="voteitem">
</BODY>
</HTML>
View Code

ReVote.php    重新投票处理模块(处理AddItem.php中的重新投票按钮,将投票项目的VoteCount设置为0,重新计数)

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″> 
<?PHP
    include('Class\VoteItem.php');
    $objItem = new VoteItem();
    $objItem->clearCount();        // 清空计数
    include('Class\VoteIP.php');
    $objIP = new VoteIP();
    $objIP->deleteAll();                // 删除投票的IP
    echo("系统重新投票!");
?>
<script language=javascript>
opener.location.href="AddItem.php";
setTimeout("window.close()",100);
</script>
View Code

 

index.php    投票界面模块

<?PHP
    $isvoted = 0;
    
    include('Class\VoteIP.php');
    include('Class\VoteItem.php');
    $objItem = new VoteItem();
    $ItemCount = $objItem->getItemCount();
    if($ItemCount == 0)
        echo("现在没有投票项目");
    else {
        $results = $objItem->load_VoteItem();
?>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″> 
<link href="style.css" type="text/css" rel=stylesheet>
<title>投票系统</title>
<script language="javascript">
//取得被投票项目的编号,打开新窗口,查看投票结果
function SelectChk()
{
    var s=false;
    var deptid,n=0;
    var strid,strurl;
    var nn = self.document.all.item("poster");
    var j;
    for (j=0;j<nn.length;j++)
    {
        //if (self.document.all.item("poster",j).checked)
        if (nn[j].checked)
        {
            n = n + 1;
            s=true;
             
            //deptid = self.document.all.item("poster",j).id+"";
            deptid = nn[j].id+"";
            
            if(n==1)
            {
                strid = deptid;
            }
            else
            {
                strid = strid + "," + deptid;
            }
        }
    }
    strurl = "postvote.php?cid=" + strid;
    if(!s)    {
        alert("请选择投票项目!");
        return false;
    }
    window.open(strurl,"newwin","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=300");
    return false;    
}
function newwin(url) {
  var oth="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,left=200,top=200";
  oth = oth+",width=400,height=300";
  var newwin=window.open(url,"newwin",oth);
  newwin.focus();
  return false;
}

</script>
</head>
<body topmargin="2" leftmargin="2">
<form method=post  id="form1"><center>
<table border="0" width="50%" cellpadding="0" cellspacing="4">
  <tr>
    <td width="100%">
      <table border="0" width="100%" cellspacing="0" cellpadding="0" style="background-color:#B0DCF0;border: 1 dotted #A7D8EF">
        <tr>
          <td width="100%">
            <table border="0" width="100%" cellspacing="1" cellpadding="3">
              <tr>
                <td bgcolor="#FFFFFF" valign="top">
                  <table border="0" width="100%" cellspacing="1" style="background-color:#B0DCF0;border: 1 dotted #A7D8EF">
                    <tr>
                      <td width="100%" align=center>投票项目(您认为本网站下面的栏目哪个比较满意)</td>
                    </tr>
                    
<?PHP
    //取得当前投票人的ip地址,判断是否已经投票完毕                      
    $ip = $_SERVER["REMOTE_ADDR"];
    $objIP = new VoteIP();
    if($objIP->exists($ip))
        $isvoted = 1;
    
    while($row = $results->fetch_row())  {
?>              
    <tr><td bgcolor="#FFFFFF">
    <?PHP if($isvoted==0) { // 如果没有投过票,则显示复选框 ?>
    <input type="checkbox" name="poster" id="<?PHP echo($row[0]); ?>">
    <?PHP 
        } // end of if
        echo($row[1]); ?></td>
    </tr>
<?PHP
    }  // end of while
?>
     <tr>
       <td align="center">
     <?PHP
        // 判断是否已经投票完毕                      
        if($isvoted==1)  {  ?>
            您已经投过票了&nbsp;&nbsp;<a href=default.php onclick="return newwin(this.href)"><font color=blue>查看投票结果</font></a>
    <?php    }
        else {             
        ?>    <input class=submit type=submit value="投 票 " name=submit onclick="return SelectChk();">
    <?php    }
     ?>
        </td>
      </tr>
                  </table>
                </td>
              </tr>
                </table>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
<?PHP
    }
?>
</center>
<input type=hidden  name="poster">
</form><body>
</html>
View Code

 

postvote.php  处理投票模块(投票提交给postvote.php,postvote.php会重新获取投票人IP地址,通过判断表VoteIP是否存在该IP,如没有相应项目VoteCount加1)

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″> 
<?PHP
    $ip = $_SERVER["REMOTE_ADDR"];
    include('Class\VoteIP.php');
    $objIP = new VoteIP();
    // 如果表中没有投过票,则插入记录
    if($objIP->exists($ip))  {
        echo("你已经投过票了,不得重复投票!");
    }
    else {
        $objIP->IP = $ip;
        $objIP->insert();
        // 投票项目数量加1
        $ids = $_GET["cid"];
        include('Class\VoteItem.php');
        $objItem = new VoteItem();
        $objItem->updateCount($ids);
        echo("已成功投票");
    }
?>
<script language=javascript>
  setTimeout("window.close()",800);
opener.location.reload();
</script>
View Code

 

default.php    显示投票结果模块(弹窗查看投票结果和投票比率)

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″> 
<link href="style.css" type="text/css" rel=stylesheet>
<title>投票系统</title>
</head>
<body topmargin="2" leftmargin="2">
<form method=post  id="form1"><center>
<table border="0" width="98%" cellpadding="0" cellspacing="4">
  <tr>
    <td width="100%">
      <table border="0" width="100%" cellspacing="0" cellpadding="0" style="background-color:#B0DCF0;border: 1 dotted #A7D8EF">
        <tr>
          <td width="100%">
            <table border="0" width="100%" cellspacing="1" cellpadding="3">
              <tr>
                <td bgcolor="#FFFFFF" valign="top">
                  <table border="0" width="100%" cellspacing="1" style="background-color:#B0DCF0;border: 1 dotted #A7D8EF">
                    <tr>
                      <td width="40%">投票项目</td>
                      <td width="40%" colspan="2">所占总投票数百分比</td>
                      <td width="10%">票数</td>
                    </tr>
                    
<?PHP
    // 取得这批投票总数
    include('Class\VoteItem.php');
    $objItem = new VoteItem();
    $total = $objItem->SumItemCount();

    // 取得每个投票项目信息
    $results = $objItem->load_VoteItem();
    while($row = $results->fetch_row())  {
        if($total == 0)
            $itotal = 1;
        else 
            $itotal = $total;
        
        // 计算每个投票项目百分比图片长度
        $imgvote = (int)$row[2] * 170 / $itotal;
?>
              
    <tr><td bgcolor="#FFFFFF"><?PHP echo($row[1]);?></td>
    <td colspan="2" bgcolor="#FFFFFF">
       <img src=images/bar1.gif width=<?PHP echo($imgvote); ?> height=10><font style="font:7pt" face="Verdana">
       <?PHP echo((int)$row[2]*100/$itotal); ?>%</font></td>
    <td bgcolor="#FFFFFF" align="center"><?PHP echo($row[2]); ?></td>
    </tr>
<?PHP } // end of while ?>
     <tr> <td colspan="2" align="left"></td>
      <td colspan="2" align="right">总票数:<?PHP echo($total); ?></td>

                    </tr>
                  </table>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</center>
<input type=hidden  name="poster">
</form><body>
<script language=javascript>
opener.location.reload();
</script>
</html>
View Code

 


 

截图:

投票项目管理


 


 

投票界面

 


 

显示投票结果

 

posted @ 2015-07-07 13:42  月之漫步  阅读(848)  评论(0编辑  收藏  举报