1. 程式人生 > >php結合mysql和jquery做簡單的投票小程式

php結合mysql和jquery做簡單的投票小程式

  首先在資料庫中要有張表,欄位為id,name(即投票的選項),count(各選項所投票的數量累計)。
具體思路:當選項被選中時,count+1,count的值作為div的長度顯示在html頁面中,可以巢狀兩個div,外div長度固定,內div的長度設定為百分比,這樣就可以顯示百分比了。
具體程式碼如下:

HTML頁面(包括js):

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>投票</title>
//引用jquery
<script type="text/javascript" src="../../jquery-3.2.1.min.js"></script>
//為當做統計條的div設定一下樣式
<style>
.wai{
width: 100px;
height: 15px;
border: 1px solid red;
}
.nei{
width: 1%;
height: 15px;
background: red;
}
</style>

</head>

<body>

<h1>投票</h1>
<div id="show1"></div>
<div id="show2">
    <table></table>
</div>

<button onClick="tijiao()">提交</button>
</body>
</html>
<script>
var attr=[];
var sum=0;
ajax獲取資料
$.ajax({
    async:true,
    url:'untitled.php',  
    data:{type:'select'},
    type:'post',
    dataType:'text',
    success:function(data){
//把php返回的字串轉成二維陣列
    strToArr(data);
    }
});
//方法:字串轉陣列
function strToArr(str){
    var arr=str.split('^'),
        brr=[],
        sum=0;
    for(var i in arr){
        brr.push(arr[i].split(','));
        sum+=+brr[i][2];
    }
    attr=brr;
    initHtml(sum);
}
//方法:將資料列印至HTML頁面中(包括選項)
function initHtml(sum){
    var str='';
    for(var i in attr){
    str+='<input type="checkbox" data-id="'+attr[i][0]+'">'+attr[i][1]+'<br>';
    }
    $('#show1').html(str);
    str='';
    for(var i in attr){
        str+=`<tr>
            <td>`+attr[i][1]+`</td>
            <td>
                <div class="wai">
                    <div class="nei" style="width:`+((attr[i][2]/sum)*100).toFixed(2)+`%;"></div>
                 </div>
            </td>
            <td>`+attr[i][2]+`(`+((attr[i][2]/sum)*100).toFixed(2)+`%)</td>
        </tr>`;
    }
    $('#show2 table').html(str);
}
//提交按鈕的方法
function tijiao(){
    var str='';
    $('input:checkbox:checked').each(function(){
        str+=$(this).attr('data-id')+',';
    })
    str=str.substring(0,str.length-1);
    $.ajax({
    async:true,  
    url:'index.php',
    data:{type:'insert',ids:str},
    type:'post',  
    dataType:'text',
    success:function(data){
//把php返回的字串轉成二維陣列
    strToArr(data);
    }
});
}

</script>

php頁面:

<?php

$db= new MySQLi('localhost','root','root','database');
!mysqli_connect_error() or die('連線失敗');
$db->query('set names utf8');

$type=$_REQUEST['type'];

switch($type){
    case 'insert':
        $ids=$_POST['ids'];
        $sql="update table set count= count+1 where id in ($ids) ";
        $db->query($sql);
    break;
    case 'select':

        
    break;

}
        $sql="select * from table";
        $res=$db->query($sql);
        $attr=$res->fetch_all();

        // 陣列轉字串
        $brr=array();
        foreach($attr as $v){
            $brr[]=implode(",",$v);
        }
        echo implode('^',$brr);