admin.php
<?php
include_once 'checkAdmin.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>我最爱的汽车投票</title>
<style>
h1,h2{text-align: center}
h2{font-size: 20px;}
h2 a{text-decoration: none;color: #4476A7;}
h2 a:hover{text-decoration: underline;color: brown}
.img{width: 100%;max-width: 150px;}
.current{color: blueviolet}
</style>
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script src="layer/layer.js"></script>
</head>
<body>
<h1>车辆管理</h1>
<h2><a href="index.php">返回首页</a> <a href="admin.php" class="current">车辆管理</a> <a href="show.php">数据查看</a> <a href="logout.php.php">注销</a></h2>
<?php
include_once 'conn.php';
include_once 'page.php';
$sql = "select count(id) as total from carinfo";//使用聚合函数count统计记录总数
$result = mysqli_query($conn, $sql);
$info = mysqli_fetch_array($result);
$total = $info['total']; //得到记录总数
$perPage = 4; //设置每一页显示多少条数据
$page = $_GET['page'] ?? 1; //读取当前页码
paging($total, $perPage);//引用分页函数
$sql = "select * from carinfo order by id desc limit $firstCount,$displayPG";
$result = mysqli_query($conn, $sql);
?>
<table border="0" width="100%" align="center">
<tr><td>
<table align="center" width="100%" border="1" bordercolor="black" cellspacing="0" cellpadding="10" style="border-collapse: collapse">
<tr>
<td align="center" width="8%">序号</td>
<td align="center" width="20%">车辆名称</td>
<td align="center" width="39%">车辆描述</td>
<td align="center" width="10%">车辆图片</td>
<td align="center" width="8%">当前票数</td>
<td align="center" width="15%">操作</td>
</tr>
<?php
$i = ($page - 1) * $perPage + 1;
while($info = mysqli_fetch_array($result)){
?>
<tr>
<td align="center"><?php echo $i;?></td>
<td align="center"><?php echo $info['carName'];?></td>
<td align="center" ><?php echo $info['carDesc'];?></td>
<td align="center"><img class="img" src="img/<?php echo $info['carPic'];?>"></td>
<td align="center"><?php echo $info['carNum'];?></td>
<td align="center"><a href="modifyCar.php?id=<?php echo $info['id'];?>">修改资料</a> <a href="javascript:del('<?php echo $info['carName'];?>',<?php echo $info['id'];?>)">删除资料</a></td>
</tr>
<?php
$i++;
}
?>
</table>
</td></tr>
<tr>
<td align="right">
<?php
echo $pageNav;
?>
</td>
</tr>
<tr>
<td>
<h2>车辆添加</h2>
<form onsubmit="return check()" enctype="multipart/form-data" method="post" action="postAddCar.php">
<table width="70%" align="center" style="border-collapse: collapse;" border="1" bordercolor="gray" cellpadding="10" cellspacing="0" >
<tr>
<td align="right">车辆名称</td>
<td align="left"><input name="carName" id="carName"></td>
</tr>
<tr>
<td align="right">车辆描述</td>
<td align="left"><textarea name="carDesc" id="carDesc"></textarea></td>
</tr>
<tr>
<td align="right">车辆图片</td>
<td align="left"><input type="file" id="carPic" name="carPic"></td>
</tr>
<tr>
<td align="right"><input type="submit" value="添加"></td>
<td align="left"><input type="reset" value="重置"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<script>
function del(name,id){
layer.confirm('您确认要删除车辆 ' + name + ' ?', {icon: 3, title:'提示'}, function(index){
location.href = 'delCar.php?id='+id;
layer.close(index);
});
}
function check(){
let carName = $("#carName").val().trim();
let carDesc = $("#carDesc").val().trim();
let carPic = $("#carPic").val().trim();
if(carName == '' || carDesc == '' || carPic == ''){
alert('车辆名称、车辆描述、车辆图片都必须要填写');
return false;
}
return true;
}
</script>
</body>
</html>
ajaxVote.php
<?php
//ajaxVote 判断了是否可以直接通过URLsql进入
session_start();
$a = array();
if(!isset($_SESSION['loggedUsername']) || !$_SESSION['loggedUsername']){
$a['error'] = 1;
$a['errMsg'] = '请登录后访问本页面';
echo json_encode($a);
exit;
}
include_once 'conn.php';
$id = $_GET['id'] ?? '';
$code = $_GET['code'];
//判断验证码是否正确
if(strtolower($_SESSION['captcha']) == strtolower($code)){
$_SESSION['captcha'] = '';
}
else{
$_SESSION['captcha'] = '';
$a['error'] = 1;
$a['errMsg'] = '验证码错误';
echo json_encode($a);
exit;
}
if(!is_numeric($id) || $id == ''){
$a['error'] = 1;
$a['errMsg'] = '参数错误';
echo json_encode($a);
exit;
}
//投票条件判断
$sql = "select count(1) as num from votedetail where userID = ".$_SESSION['loggedUserID']." and carID = $id and FROM_UNIXTIME(voteTime,'%Y-%m-%d') = '".date("Y-m-d")."'";
$result = mysqli_query($conn,$sql);
$info = mysqli_fetch_array($result);
if($info['num'] == 5){
//说明当前用户给当前车辆已经投过5票了
$a['error'] = 1;
$a['errMsg'] = '当前用户给当前车辆已经投过5票了';
echo json_encode($a);
exit;
}
//第2个条件
//要求一人一天最多可以给三辆车投票
$sql = "select carID from votedetail where userID = ".$_SESSION['loggedUserID']." and FROM_UNIXTIME(voteTime,'%Y-%m-%d') = '".date("Y-m-d")."' and carID <> $id group by carID";
$result = mysqli_query($conn,$sql);
$num = mysqli_num_rows($result);
if($num >= 3){ //排除当前投票车辆以后,还发现已经给三辆车投过票了,则说明当前是第4辆车,无法投票。
$a['error'] = 1;
$a['errMsg'] = '每人每天最多只能给三辆车投票';
echo json_encode($a);
exit;
}
//第3个条件
//两次投票之间要求间隔60s以上。
$sql = "select voteTime from votedetail where userID = " . $_SESSION['loggedUserID'] . " order by id desc limit 0,1";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
//说明此用户曾经投过票
$info = mysqli_fetch_array($result);
if(time() - $info['voteTime'] <= 10){
//说明投票间隔未超过60s,不可以投票
$a['error'] = 1;
$a['errMsg'] = '两次投票之间,必须间隔10s。';
echo json_encode($a);
exit;
}
}
//第4个条件
//IP投票限制。限制一个IP一天只能投15票
$sql = "select 1 from votedetail where from_unixtime(voteTime,'%Y-%m-%d') = CURRENT_DATE() and ip = '".getIp()."'";
if(mysqli_num_rows($result)>=15){
//说明当前IP地址已经投过15票了
$a['error'] = 1;
$a['errMsg'] = '一个IP地址一天之内最多只能投15票。';
echo json_encode($a);
exit;
}
//确认可以投票
//第1步操作,更新carnum
$sql1 = "update carinfo set carnum = carNum + 1 where id = $id";
//第2步操作,更新votedteail表
$sql2 = "insert into votedetail (userID, carID, voteTime, ip) VALUES ('".$_SESSION['loggedUserID']."','$id','".time()."','".getIp()."')";
//引入事务机制
mysqli_autocommit($conn,0); //取消自动提交
$result1 = mysqli_query($conn,$sql1);
//echo "1:".mysqli_error($conn);
$result2 = mysqli_query($conn,$sql2);
//echo "2:".mysqli_error($conn);
if($result1 and $result2){
mysqli_commit($conn);//提交操作
$a['error'] = 0;
echo json_encode($a);
}
else{
mysqli_rollback($conn);
$a['error'] = 1;
$a['errMsg'] = '投票失败';
echo json_encode($a);
}
function getIp()
{
if ($_SERVER["HTTP_CLIENT_IP"] && strcasecmp($_SERVER["HTTP_CLIENT_IP"], "unknown")) {
$ip = $_SERVER["HTTP_CLIENT_IP"];
} else {
if ($_SERVER["HTTP_X_FORWARDED_FOR"] && strcasecmp($_SERVER["HTTP_X_FORWARDED_FOR"], "unknown")) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
if ($_SERVER["REMOTE_ADDR"] && strcasecmp($_SERVER["REMOTE_ADDR"], "unknown")) {
$ip = $_SERVER["REMOTE_ADDR"];
} else {
if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'],
"unknown")
) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = "unknown";
}
}
}
}
return ($ip);
}
checkAdmin.php
<?php
//首先判断是不是管理员,很多页面需要管理员时候调用
session_start();
if(!isset($_SESSION['isAdmin']) || !$_SESSION['isAdmin']){
//说明isAdmin不存在或者存在,但值为0
echo "<script>alert('请以管理员身份登录后访问本页面');location.href='login.php';</script>";
exit;
}
checkLogin
<?php
//首先判断是不是登录了
session_start();
if(!isset($_SESSION['loggedUsername']) || !$_SESSION['loggedUsername']){
echo "<script>alert('请登录后访问本页面');location.href='login.php';</script>";
exit;
}
checkUsername
<?php
include_once 'conn.php';
$username = $_POST['username'];
$a = array();
if(empty($username)){
$a['code'] = 1;
$a['msg'] = '用户名不能为空';
}
else{
$sql = "select 1 from userinfo where username = '$username'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
//找到了此用户名,则说明此用户名不可用
$a['code'] = 0;
$a['msg'] = '此用户名不可用';
}
else{
$a['code'] = 2;
$a['msg'] = '此用户名可用';
}
}
echo json_encode($a);
code
<?php
/**
* 字母+数字的验证码生成
*/
// 开启session
session_start();
//1.创建黑色画布
$image = imagecreatetruecolor(100, 30);
//2.为画布定义(背景)颜色
$bgcolor = imagecolorallocate($image, 255, 255, 255);
//3.填充颜色
imagefill($image, 0, 0, $bgcolor);
// 4.设置验证码内容
//4.1 定义验证码的内容
$content = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789";
//4.1 创建一个变量存储产生的验证码数据,便于用户提交核对
$captcha = "";
for ($i = 0; $i < 4; $i++) { //验证码长度为4
// 字体大小
$fontsize = 10;
// 字体颜色
$fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
// 设置字体内容
$fontcontent = substr($content, mt_rand(0, strlen($content)), 1);
$captcha .= $fontcontent;
// 显示的坐标
$x = ($i * 100 / 4) + mt_rand(5, 10);
$y = mt_rand(5, 10);
// 填充内容到画布中
imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}
$_SESSION["captcha"] = $captcha;
//4.3 设置背景干扰元素
for ($i = 0; $i < 200; $i++) {
$pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
imagesetpixel($image, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
}
//4.4 设置干扰线
for ($i = 0; $i < 3; $i++) {
$linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
imageline($image, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $linecolor);
}
//5.向浏览器输出图片头信息
header('content-type:image/png');
//6.输出图片到浏览器
imagepng($image);
//7.销毁图片
imagedestroy($image);
conn
<?php
$conn = mysqli_connect('localhost','root','shujuku','vote') or die('数据库连接失败');
mysqli_query($conn,'set names utf8');
delCar
<?php
include_once 'checkAdmin.php';
$id = $_GET['id'] ?? 0;
include_once 'conn.php';
$sql = "delete from carinfo where id = $id";
$result = mysqli_query($conn,$sql);
if($result){
echo "<script>alert('删除成功');location.href='admin.php';</script>";
}
else{
echo "<script>alert('删除失败');history.back();</script>";
}
index
<?php
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<title>我最爱的汽车投票</title>
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
<script src="layer/layer.js"></script>
<style>
.login{text-align: right;margin-bottom: 20px;}
.img{position: relative}
.row img{width: 100%;}
.img .row{position: absolute;bottom: 0;left: 15px;background-color: rgba(0,0,0,0.5);width: 100%;color: white;}
p{margin: 10px 0 !important;}
.code td{padding: 10px !important;}
</style>
</head>
<body>
<div class="container">
<h1 class="text-center">我最爱的车辆投票</h1>
<p class="login">
<?php
//通过判断session来说明是否登录,已经登陆则
if(isset($_SESSION['loggedUsername']) and $_SESSION['loggedUsername'] != ''){
//说明已经登录了则显示表单栏 实现各种的链接(注销注册修改资料等等)
?>
当前登录者:<?php echo $_SESSION['loggedUsername'];?> <a href="logout.php">注销</a> <a href="javascript:open('singup.php','用户注册')">注册</a> <a href="javascript:open('modify.php','修改资料')">修改资料</a> <?php if($_SESSION['isAdmin']){?><a href="admin.php">后台管理</a><?php }?>
<?php
}
else{
//登录失败则返回到用户登录页面
?>
<a href="javascript:open('login.php','用户登录')">登录</a> <a href="javascript:open('singup.php','用户注册')">注册</a>
<?php
}
?>
</p>
<div class="row">
<?php
include_once 'conn.php';
$sql = "select * from carinfo order by id desc ";
$result = mysqli_query($conn,$sql);
$i = 1;
while($info = mysqli_fetch_array($result)){
?>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">
<div class="img">
<?php
if(isset($_SESSION['loggedUsername']) and $_SESSION['loggedUsername'] != ''){
//说明已经登录了
?>
<a href="javascript:showCode(<?php echo $info['id'];?>)"><img src="img/<?php echo $info['carPic'];?>"></a>
<?php
}
else{
?>
<img src="img/<?php echo $info['carPic'];?>">
<?php
}
?>
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6">
<p class="text-center"><?php echo $info['carName'];?></p>
</div>
<div class="col-xs-12 col-sm-4 col-md-6">
<p class="text-center">当前票数:<span id="num<?php echo $info['id'];?>"><?php echo $info['carNum'];?></span></p>
</div>
</div>
</div>
<p><?php echo $info['carDesc'];?></p>
</div>
<?php
if($i % 2 == 0){
echo '<div class="clearfix visible-sm-block"></div>';
}
if($i %3 == 0){
echo '<div class="clearfix visible-md-block"></div>';
}
if($i %4 == 0){
echo '<div class="clearfix visible-lg-block"></div>';
}
$i++;
}
?>
</div>
</div>
<script>
function showCode(id){
let str = '';
str += '<div class="code">';
//str += '<form action="vote.php" method="GET">';
str += '<table style="border-collapse: collapse" border="1" bordercolor = "gray" cellspacing="0">';
str += '<tr>';
str += '<td align="right">验证码</td>';
str += '<td align="left"><input name="code" id="code"><img src="code.php" id="codeIMG"><input type="hidden" name="id" id="carID"> </td>';
str += '</tr>';
str += '<tr>';
str += '<td align="right"><input type="button" id="postVote" value="提交"></td>';
str += '<td align="left"><input type="reset" value="重置"></td>';
str += '</tr>';
str += '</table>'
//str += '</form>';
str += '</div>';
layer.open({
type: 1,
title: '请输入验证码',
shadeClose: false,
closeBtn :2,
content: str,
success: function(layero, index){
$("#postVote").click(function (){
$.ajax({
url:'ajaxVote.php',
data:{id:id,code:$("#code").val().trim()},
dataType:'json',
type:'GET',
success:function (d){
if(d.error == 1){
//说明出错
layer.alert(d.errMsg, {icon: 2},function(index){
layer.closeAll();
});
}
else{
let num = parseInt($("#num" + id).text());
$("#num" + id).text(num + 1);
layer.alert('投票成功', {icon: 1},function(index){
layer.closeAll();
});
}
},
error:function (){
layer.alert(d.errMsg, {icon: 3},function(index){
layer.closeAll();
});
}
})
})
$("#codeIMG").click(function (){
$(this).attr('src','code.php?id='+new Date());
})
}
});
}
function open(url,title){
layer.open({
type: 2,
title:title,
area: ['700px', '450px'],
fixed: false, //不固定
maxmin: true,
content: url
});
}
$(function (){
})
function closeLayer(){
layer.closeAll();
}
</script>
</body>
</html>
login
<?php
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>会员管理系统</title>
<style>
.main{width: 80%;margin: 0 auto;text-align: center;}
h2{font-size: 20px}
h2 a{color: navy;text-decoration: none;margin-right: 15px}
h2 a:last-child{margin-right: 0}
h2 a:hover{color: brown;text-decoration: underline}
.current{color: brown}
.red{color: red}
.none{width: 20px;display: none}
</style>
</head>
<body>
<div class="main">
<form action="postLogin.php" method="post" onsubmit="return check()">
<table align="center" border="1" style="border-collapse: collapse" cellpadding="10" cellspacing="0">
<tr>
<td align="right">用户名</td>
<td align="left"><input name="username" id="username" onblur="checkUsername()"><span class="red">*</span><img src="img/x0.png" id="x0" class="none">
<img src="img/x1.png" id="x1" class="none"></td>
</tr>
<tr>
<td align="right">密码</td>
<td align="left">
<input type="password" name="pw">
<span class="red">*</span>
</td>
</tr>
<tr>
<td align="right">验证码</td>
<td align="left">
<input name="code" placeholder="请输入图片中的验证码"><img style="cursor: pointer" src="code.php" onclick="this.src='code.php?'+new Date().getTime();" width="200" height="70">
<span class="red">*</span>
</td>
</tr>
<tr>
<td align="right"><input type="submit" value="提交"></td>
<td align="left">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</div>
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>
function checkUsername(){
let username = $("#username").val().trim();
if(username.length == 0){
$("#x0").hide();
$("#x1").hide();
return;
}
else{
let usernameReg = /^[a-zA-Z0-9]{3,10}$/;
if(!usernameReg.test(username)){
alert('用户只能由大小写字符和数字构成,长度为3到10个字符!');
return;
}
$.ajax({
url:'checkUsername.php',
type:"post",
dataType:'json',
data:{username:username},
success:function (d){
if(d.code == 0){
//表明用户名正确
$("#x0").hide();
$("#x1").show();
}
else if(d.code == 2){
//说明用户名不正确
$("#x0").show();
$("#x1").hide();
}
},
error:function (){
$("#x0").hide();
$("#x1").hide();
}
})
}
}
function check(){
let username = document.getElementsByName('username')[0].value.trim();
let pw = document.getElementsByName('pw')[0].value.trim();
//用户名验证
let usernameReg = /^[a-zA-Z0-9]{3,10}$/;
if(!usernameReg.test(username)){
alert('用户名必填,且只能大小写字符和数字构成,长度为3到10个字符!');
return false;
}
let pwreg = /^[a-zA-Z0-9_*]{6,10}$/;
if(!pwreg.test(pw)){
alert('密码必填,且只能大小写字符和数字,以及*、_构成,长度为6到10个字符!');
return false;
}
let code = document.getElementsByName('code')[0].value.trim();
let codeReg = /^[a-zA-Z0-9]{4}$/;
if(!codeReg.test(code)){
alert('验证码必填,且只能由大小写字符和数字构成,长度为4个字符!');
return false;
}
return true;
}
</script>
</body>
</html>
modify
<?php
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>会员管理系统</title>
<style>
.main{width: 80%;margin: 0 auto;text-align: center;}
h2{font-size: 20px}
h2 a{color: navy;text-decoration: none;margin-right: 15px}
h2 a:last-child{margin-right: 0}
h2 a:hover{color: brown;text-decoration: underline}
.current{color: brown}
.red{color: red}
</style>
</head>
<body>
<div class="main">
<?php
include_once 'conn.php';
$sql = "select * from userinfo where username = '".$_SESSION['loggedUsername']."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
$info = mysqli_fetch_array($result);
}
else{
die("未找到有效用户!");
}
?>
<form action="postModify.php" method="post" onsubmit="return check()">
<table align="center" border="1" style="border-collapse: collapse" cellpadding="10" cellspacing="0">
<tr>
<td align="right">用户名</td>
<td align="left"><input name="username" readonly value="<?php echo $info['userName'];?>"></td>
</tr>
<tr>
<td align="right">密码</td>
<td align="left"><input type="password" name="pw" placeholder="不修改密码请留空"></td>
</tr>
<tr>
<td align="right">确认密码</td>
<td align="left"><input type="password" name="cpw" placeholder="不修改密码请留空"></td>
</tr>
<tr>
<td align="right">信箱</td>
<td align="left"><input name="email" value="<?php echo $info['email'];?>"></td>
</tr>
<tr>
<td align="right"><input type="submit" value="提交"></td>
<td align="left">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</div>
<script>
function check(){
let pw = document.getElementsByName('pw')[0].value.trim();
let cpw = document.getElementsByName('cpw')[0].value.trim();
let email = document.getElementsByName('email')[0].value.trim();
let pwreg = /^[a-zA-Z0-9_*]{6,10}$/;
if(pw.length > 0){
if(!pwreg.test(pw)){
alert('密码必填,且只能大小写字符和数字,以及*、_构成,长度为6到10个字符!');
return false;
}
else{
if(pw!=cpw){
alert('密码和确认密码必须相同!')
return false;
}
}
}
let emailReg = /^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
if(email.length > 0 ){
if(!emailReg.test(email)){
alert('信箱格式不正确!')
return false;
}
}
return true;
}
</script>
</body>
</html>
modifyCar
<?php
include_once 'checkAdmin.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>我最爱的汽车投票</title>
<style>
h1,h2{text-align: center}
h2{font-size: 20px;}
h2 a{text-decoration: none;color: #4476A7;}
h2 a:hover{text-decoration: underline;color: brown}
.img{width: 100%;max-width: 250px;}
.current{color: blueviolet}
</style>
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<h1>车辆管理</h1>
<h2><a href="index.php">返回首页</a> <a href="admin.php" class="current">车辆管理</a> <a href="show.php">数据查看</a> <a href="logout.php.php">注销</a></h2>
<?php
include_once 'conn.php';
$id = $_GET['id'] ?? 0;
$sql = "select * from carinfo where id = $id";
$result = mysqli_query($conn,$sql);
if(!mysqli_num_rows($result)){
echo "<script>alert('未查询到当前车辆');history.back();</script>";
exit;
}
$info = mysqli_fetch_array($result);
?>
<h2>车辆资料修改</h2>
<form onsubmit="return check()" enctype="multipart/form-data" method="post" action="postModifyCar.php">
<table width="70%" align="center" style="border-collapse: collapse;" border="1" bordercolor="gray" cellpadding="10" cellspacing="0" >
<tr>
<td align="right">车辆名称</td>
<td align="left"><input name="carName" id="carName" value="<?php echo $info['carName'];?>"></td>
</tr>
<tr>
<td align="right">车辆描述</td>
<td align="left"><textarea name="carDesc" id="carDesc"><?php echo $info['carDesc'];?></textarea></td>
</tr>
<tr>
<td align="right">车辆图片</td>
<td align="left"><input type="file" id="carPic" name="carPic">
<img class="img" src="img/<?php echo $info['carPic'];?>"
</td>
</tr>
<tr>
<td align="right">
<input type="submit" value="修改">
<input type="hidden" name="id" value="<?php echo $info['id'];?>">
</td>
<td align="left"><input type="reset" value="重置"></td>
</tr>
</table>
</form>
<script>
function check(){
let carName = $("#carName").val().trim();
let carDesc = $("#carDesc").val().trim();
let carPic = $("#carPic").val().trim();
if(carName == '' || carDesc == ''){
alert('车辆名称、车辆描述都必须要填写');
return false;
}
return true;
}
</script>
</body>
</html>
page
<?php
//为了避免重复包含文件而造成错误,加了判断函数是否存在的条件:
if(!function_exists('paging')){
//定义函数paging(),三个参数的含义为:
//$total:记录总数;
//$displayPG:每页显示记录数,这里设置为默认是20;
//$url:分页导航中的链接,除了加入不同的查询信息“page”外的部分都与这个URL相同。
// 默认值本该设为本页URL(即$_SERVER["REQUEST_URI"]),但设置默认值的右边只能为常量,所以该默认值设为空字符串,在函数内部再设置为本页URL。
function paging($total,$displayPG = 20,$url = ''){
//定义几个全局变量:
//$page:当前页码;
//$firstCount:(数据库)查询的起始项;
//$pageNav:页面导航条代码,函数内部并没有将它输出;
//$_SERVER:读取本页URL“$_SERVER["REQUEST_URI"]”所必须。
global $page,$firstCount,$pageNav,$_SERVER;
//为使函数外部可以访问这里的“$displayPG”,将它也设为全局变量。注意一个变量重新定义为全局变量后,原值被覆盖,所以这里给它重新赋值。
$GLOBALS["displayPG"]=$displayPG;
$page= $_GET['page'] ?? 1;
//echo "page:".$page."<br>";
//如果$url使用默认,即空值,则赋值为本页URL:
if(!$url){
$url=$_SERVER["REQUEST_URI"];
}
//echo "url:".$url."<br>";
//URL分析:
$parse_url=parse_url($url);
/*echo "parse_url:";
print_r($parse_url);
echo "<br>";*/
$url_query = $parse_url["query"] ?? ''; //单独取出URL的查询字串
//echo "url_query:".$url_query."<br>";
if($url_query){
//因为URL中可能包含了页码信息,我们要把它去掉,以便加入新的页码信息。
//这里用到了正则表达式
$url_query=preg_replace("/(^|&)page=$page/","",$url_query);
//echo "url_query1:".$url_query."<br>";
//将处理后的URL的查询字串替换原来的URL的查询字串:
$url=str_replace($parse_url["query"],$url_query,$url);
//echo "url:".$url."<br>";
//在URL后加page查询信息,但待赋值:
if($url_query) $url.="&page"; else $url.="page";
} else {
$url.="?page";
}
//echo "url:".$url."<br>";
$lastpg=ceil($total/$displayPG); //最后页,也是总页数
$page=min($lastpg,$page);
$prepg=$page-1; //上一页
$nextpg=($page==$lastpg ? 0 : $page+1); //下一页
$firstCount=($page-1)*$displayPG;
//开始分页导航条代码:
$pageNav="第 <B>".($total?($firstCount+1):0)."</B>-<B>".min($firstCount+$displayPG,$total)."</B> 条,共<B> $total </B>条记录";
//如果只有一页则跳出函数:
if($lastpg<=1) return false;
$pageNav.=" <a href=$url=1 mce_href=$url=1>首页</a> ";
if($prepg) $pageNav.=" <a href=$url=$prepg mce_href=$url=$prepg>上页</a> "; else $pageNav.=" 上页 ";
if($nextpg) $pageNav.=" <a href=$url=$nextpg mce_href=$url=$nextpg>下页</a> "; else $pageNav.=" 下页 ";
$pageNav.=" <a href=$url=$lastpg mce_href=$url=$lastpg>尾页</a> ";
//下拉跳转列表,循环列出所有页码:
$pageNav.=" 到第 <select name='topage' size='1' style='font-size:12px' mce_style='font-size:12px' onchange='window.location=\"$url=\"+this.value'>\n";
for($i=1;$i<=$lastpg;$i++){
if($i==$page) $pageNav.="<option value='$i' selected>$i</option>\n";
else $pageNav.="<option value='$i'>$i</option>\n";
}
$pageNav .="</select> 页,共 $lastpg 页";
}
}
postAddCar
<?php
$carName = $_POST['carName'];
$carDesc = $_POST['carDesc'];
$fileName = '';
//print_r($_FILES['carPic']);
//第一步,判断图片上传是否有错
if($_FILES['carPic']['error']){
echo "<script>alert('图片上传错误');history.back();</script>";
exit;
}
//第二步,判断文件格式以及大小是否正确
if(!empty($_FILES['carPic']['name'])){//说明有上传图片
//先判断文件尺寸,不得大于2MB
if($_FILES['carPic']['size'] > 2048*1024){
echo "<script>alert('图片文件大小不能超过2MB');history.back();</script>";
exit;
}
//接下来判断文件格式
$allowType = array("image/gif","image/pjpeg","image/jpeg","image/jpg","image/png");
if(!in_array($_FILES['carPic']['type'],$allowType)){
echo "<script>alert('图片类型错误,只能是jpg、png、gif图片。');history.back();</script>";
exit;
}
$allowExt = array("jpg","jpeg","png","gif");
$nameArray = explode(".",$_FILES['carPic']['name']);
$nameExt = end($nameArray);
if(!in_array(strtolower($nameExt),$allowExt)){
//echo "<script>alert('图片文件扩展名错误,只能是jpg、jpeg、png、gif文件。');history.back();</script>";
exit;
}
$fileName = uniqid().".".$nameExt;//得到唯一的文件名id
$result = move_uploaded_file($_FILES['carPic']['tmp_name'],"img/".$fileName);
//将文件存到img的文档目录下面。
if(!$result){
//说明文件保存不成功
echo "<script>alert('保存文件出错。');history.back();</script>";
exit;
}
}
//第三步,写入数据库。
include_once 'conn.php';
$sql = "insert into carinfo (carName, carDesc, carPic, carNum) VALUES ('$carName','$carDesc','$fileName','0')";
$result = mysqli_query($conn,$sql);
if($result){
echo "<script>alert('车辆添加成功。');location.href='admin.php';</script>";
}
else{
echo "<script>alert('车辆添加失败。');history.back();</script>";
}
postLogin
<?php
session_start();
$username = trim($_POST['username']);
$pw = trim($_POST['pw']);
//进行必须的验证
$code = $_POST['code'];
//判断验证码是否正确
if(strtolower($_SESSION['captcha']) == strtolower($code)){
$_SESSION['captcha'] = '';
}
else{
$_SESSION['captcha'] = '';
echo "<script>alert('验证码错误');location.href='login.php?id=3';</script>";
exit;
}
if(!strlen($username) || !strlen($pw)){
echo "<script>alert('用户名和密码都必须要填写');history.back();</script>";
exit;
}
else{
if(!preg_match('/^[a-zA-Z0-9]{3,10}$/',$username)){
echo "<script>alert('用户名必填,且只能大小写字符和数字构成,长度为3到10个字符!');history.back();</script>";
exit;
}
if(!preg_match('/^[a-zA-Z0-9_*]{6,10}$/',$pw)){
echo "<script>alert('密码必填,且只能大小写字符和数字,以及*、_构成,长度为6到10个字符!');history.back();</script>";
exit;
}
}
include_once "conn.php";
$sql = "select * from userinfo where username = '$username' and pw = '" . md5($pw) . "'";
$result = mysqli_query($conn,$sql);
$num = mysqli_num_rows($result);
if($num){
$_SESSION['loggedUsername'] = $username;
//判断是不是管理员
$info = mysqli_fetch_array($result);
$_SESSION['loggedUserID'] = $info['id'];
if($info['admin']){
$_SESSION['isAdmin'] = 1;
}
else{
$_SESSION['isAdmin'] = 0;
}
echo "<script>alert('登录成功!');window.parent.location.reload();</script>";
}
else{
unset($_SESSION['isAdmin']);
unset($_SESSION['loggedUsername']);
echo "<script>alert('登录失败!');window.parent.closeLayer();</script>";
}
postModify
<?php
$username = trim($_POST['username']);
$pw = trim($_POST['pw']);
$cpw = trim($_POST['cpw']);
$email = $_POST['email'];
//进行必须的验证
if(!strlen($username)){
echo "<script>alert('用户名必须要填写');history.back();</script>";
exit;
}
else{
if(!preg_match('/^[a-zA-Z0-9]{3,10}$/',$username)){
echo "<script>alert('用户名必填,且只能大小写字符和数字构成,长度为3到10个字符!');history.back();</script>";
exit;
}
}
if(!empty($pw)){
if($pw <> $cpw){
echo "<script>alert('密码和确认密码必须相同');history.back();</script>";
exit;
}
else{
if(!preg_match('/^[a-zA-Z0-9_*]{6,10}$/',$pw)){
echo "<script>alert('密码必填,且只能大小写字符和数字,以及*、_构成,长度为6到10个字符!');history.back();</script>";
exit;
}
}
}
if(!empty($email)){
if(!preg_match('/^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/',$email)){
echo "<script>alert('信箱格式不正确!');history.back();</script>";
exit;
}
}
include_once 'conn.php';
if($pw){ //说明有填写密码,要更新密码
$sql = "update userinfo set pw = '".md5($pw)."',email = '$email' where username = '$username'";
}
else{
$sql = "update userinfo set email = '$email' where username = '$username'";
}
$result = mysqli_query($conn,$sql);
if($result){
echo "<script>alert('更新个人资料成功!');window.parent.closeLayer();</script>";
}
else{
echo "<script>alert('更新个人资料失败!');history.back();</script>";
}
postModifyCar
<?php
$id = $_POST['id'];
$carName = $_POST['carName'];
$carDesc = $_POST['carDesc'];
$fileName = '';
//print_r($_FILES['carPic']);
//exit;
//第一步,判断图片上传是否有错
if($_FILES['carPic']['error'] > 0 and $_FILES['carPic']['error'] <> 4){
echo "<script>alert('图片上传错误');history.back();</script>";
exit;
}
//第二步,判断文件格式以及大小是否正确
if(!empty($_FILES['carPic']['name'])){//说明有上传图片
//先判断文件尺寸,不得大于2MB
if($_FILES['carPic']['size'] > 2048*1024){
echo "<script>alert('图片文件大小不能超过2MB');history.back();</script>";
exit;
}
//接下来判断文件格式
$allowType = array("image/gif","image/pjpeg","image/jpeg","image/jpg","image/png");
if(!in_array($_FILES['carPic']['type'],$allowType)){
echo "<script>alert('图片类型错误,只能是jpg、png、gif图片。');history.back();</script>";
exit;
}
$allowExt = array("jpg","jpeg","png","gif");
$nameArray = explode(".",$_FILES['carPic']['name']);
$nameExt = end($nameArray);
if(!in_array(strtolower($nameExt),$allowExt)){
//echo "<script>alert('图片文件扩展名错误,只能是jpg、jpeg、png、gif文件。');history.back();</script>";
exit;
}
$fileName = uniqid().".".$nameExt;
$result = move_uploaded_file($_FILES['carPic']['tmp_name'],"img/".$fileName);
if(!$result){
//说明文件保存不成功
echo "<script>alert('保存文件出错。');history.back();</script>";
exit;
}
}
//第三步,写入数据库。
include_once 'conn.php';
if($fileName){
//说明修改资料时,用户有上传新的图片
$sql = "update carinfo set carName = '$carName',carDesc = '$carDesc',carPic = '$fileName' where id = $id";
}
else{
//说明只修改车辆名称和描述
$sql = "update carinfo set carName = '$carName',carDesc = '$carDesc' where id = $id";
}
$result = mysqli_query($conn,$sql);
if($result){
echo "<script>alert('车辆资料修改成功。');location.href='admin.php';</script>";
}
else{
echo "<script>alert('车辆资料修改失败。');history.back();</script>";
}
postReg
<!-- 登录成功后提交数据库验证是否用户存在-->
<?php
header("Content-Type:text/html;charset=utf-8");
//在后端获取前端表单数据的方法是使用全局数组$_GET或$_POST
//提交数据到数据库
$username = trim($_POST['username']);
$pw = trim($_POST['pw']);
$cpw = trim($_POST['cpw']);
$email = $_POST['email'];
//连接数据库服务器
//第一步,连接数据库服务器
$conn = mysqli_connect("localhost","root","shujuku","vote");
if(!$conn){
die("连接数据库服务器失败");
}
//第二步,设置字符集
mysqli_query($conn,"set names utf8");
//进行必须的验证
if(!strlen($username) || !strlen($pw)){
echo "<script>alert('用户名和密码都必须要填写');history.back();</script>";
exit;
}
else{
if(!preg_match('/^[a-zA-Z0-9]{3,10}$/',$username)){
echo "<script>alert('用户名必填,且只能大小写字符和数字构成,长度为3到10个字符!');history.back();</script>";
exit;
}
}
if($pw <> $cpw){
echo "<script>alert('密码和确认密码必须相同');history.back();</script>";
exit;
}
else{
if(!preg_match('/^[a-zA-Z0-9_*]{6,10}$/',$pw)){
echo "<script>alert('密码必填,且只能大小写字符和数字,以及*、_构成,长度为6到10个字符!');history.back();</script>";
exit;
}
}
if(!empty($email)){
if(!preg_match('/^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/',$email)){
echo "<script>alert('信箱格式不正确!');history.back();</script>";
exit;
}
}
//判断用户名是否重复(是否被占用)
$sql = "select * from userinfo where username = '$username'";
$result = mysqli_query($conn,$sql); //返回一个记录集
$num = mysqli_num_rows($result);
if($num){
echo "<script>alert('此用户名已经被占用了,请返回重新输入');history.back();</script>";
exit;
}
//sql语句
$sql = "insert into userinfo (username,pw,email) values ('$username','" .md5($pw). "','$email')";
$result = mysqli_query($conn,$sql);
//mysql_insert_id($conn);
if($result){
echo "<script>alert('数据插入成功');window.parent.closeLayer();</script>";
}
else{
echo "<script>alert('数据插入失败');</script>";
}
show
<?php
include_once 'checkAdmin.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>我最爱的汽车投票</title>
<style>
h1,h2{text-align: center}
h2{font-size: 20px;}
h2 a{text-decoration: none;color: #4476A7;}
h2 a:hover{text-decoration: underline;color: brown}
.current{color: blueviolet}
#main{margin: 40px auto}
</style>
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script src="js/echarts.min.js"></script>
</head>
<body>
<h1>车辆管理</h1>
<h2><a href="index.php">返回首页</a> <a href="admin.php">车辆管理</a> <a href="show.php" class="current">数据查看</a> <a href="logout.php">注销</a></h2>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 800px;height:400px;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
// 显示标题,图例和空的坐标轴
myChart.setOption({
title: {
text: '车辆票数柱状图'
},
tooltip: {},
legend: {
data:['票数']
},
xAxis: {
data: []
},
yAxis: {},
series: [{
name: '票数',
type: 'bar',
data: []
}]
});
$.ajax({
url:'getData.php',
dataType:'json',
success:function (data){
myChart.setOption({
xAxis: {
data: data.categories
},
series: [{
name: '票数',
data: data.data
}]
});
},
error:function (){
alert('获取数据出错');
}
})
</script>
</body>
</html>
singup
<?php
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>会员管理系统</title>
<style>
.main{width: 80%;margin: 0 auto;text-align: center;}
h2{font-size: 20px}
h2 a{color: navy;text-decoration: none;margin-right: 15px}
h2 a:last-child{margin-right: 0}
h2 a:hover{color: brown;text-decoration: underline}
.current{color: brown}
.red{color: red}
.green{color: green}
.black{color: black}
#loading{width: 80px;display: none}
</style>
</head>
<body>
<div class="main">
<form action="postReg.php" method="post" onsubmit="return check()">
<table align="center" border="1" style="border-collapse: collapse" cellpadding="10" cellspacing="0">
<tr>
<td align="right">用户名</td>
<td align="left"><input name="username" onblur="checkUsername()"><span class="red">*</span> <span id="usernameMsg"></span><img src="img/loading.gif" id="loading"> </td>
</tr>
<tr>
<td align="right">密码</td>
<td align="left"><input type="password" name="pw"><span class="red">*</span></td>
</tr>
<tr>
<td align="right">确认密码</td>
<td align="left"><input type="password" name="cpw"><span class="red">*</span></td>
</tr>
<tr>
<td align="right">信箱</td>
<td align="left"><input name="email"></td>
</tr>
<tr>
<td align="right"><input type="submit" value="提交"></td>
<td align="left">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</div>
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>
function checkUsername(){
let username = document.getElementsByName('username')[0].value.trim();
let usernameReg = /^[a-zA-Z0-9]{3,10}$/;
if(!usernameReg.test(username)){
alert('用户名必填,且只能由大小写字符和数字构成,长度为3到10个字符!');
$("#usernameMsg").text('');
return false;
}
$.ajax({
url:"checkUsername.php",
type:'post',
dataType:'json',
data:{username:username},
beforeSend:function (){
$("#usernameMsg").text('');
$("#loading").show();
},
success:function (data){
$("#loading").hide();
if(data.code == 0){
//表明不可用
$("#usernameMsg").text(data.msg).removeClass('black').addClass('green');
}
else if(data.code == 2){
//表明可用
$("#usernameMsg").text(data.msg).removeClass('green').addClass('black');
}
},
error:function (){
$("#loading").hide();
alert('网络错误');
}
})
}
function check(){
let username = document.getElementsByName('username')[0].value.trim();
let pw = document.getElementsByName('pw')[0].value.trim();
let cpw = document.getElementsByName('cpw')[0].value.trim();
let email = document.getElementsByName('email')[0].value.trim();
//用户名验证
let usernameReg = /^[a-zA-Z0-9]{3,10}$/;
if(!usernameReg.test(username)){
alert('用户名必填,且只能由大小写字符和数字构成,长度为3到10个字符!');
return false;
}
let pwreg = /^[a-zA-Z0-9_*]{6,10}$/;
if(!pwreg.test(pw)){
alert('密码必填,且只能大小写字符和数字,以及*、_构成,长度为6到10个字符!');
return false;
}
else{
if(pw!=cpw){
alert('密码和确认密码必须相同!')
return false;
}
}
let emailReg = /^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
if(email.length > 0 ){
if(!emailReg.test(email)){
alert('信箱格式不正确!')
return false;
}
}
return true;
}
</script>
</body>
</html>
vote
<?php
include_once 'checkLogin.php';
include_once 'conn.php';
$id = $_GET['id'] ?? '';
$code = $_GET['code'];
//判断验证码是否正确
if(strtolower($_SESSION['captcha']) == strtolower($code)){
$_SESSION['captcha'] = '';
}
else{
$_SESSION['captcha'] = '';
echo "<script>alert('验证码错误');location.href='index.php';</script>";
exit;
}
if(!is_numeric($id) || $id == ''){
echo "<script>alert('参数错误');history.back();</script>";
exit;
}
//投票条件判断
//第1个条件:一个人一天只能给一辆车最多投5票
$sql = "select count(1) as num from votedetail where userID = ".$_SESSION['loggedUserID']." and carID = $id and FROM_UNIXTIME(voteTime,'%Y-%m-%d') = '".date("Y-m-d")."'";
//将搜索到的今天投票数量 as 为num数组通过数组判断是否为5票从而限制投票
$result = mysqli_query($conn,$sql);
$info = mysqli_fetch_array($result);
if($info['num'] == 5){
//说明当前用户给当前车辆已经投过5票了
echo "<script>alert('当前用户给当前车辆已经投过5票了');history.back();</script>";
exit;
}
//第2个条件
//要求一人一天最多可以给三辆车投票
$sql = "select carID from votedetail where userID = ".$_SESSION['loggedUserID']." and FROM_UNIXTIME(voteTime,'%Y-%m-%d') = '".date("Y-m-d")."' and carID <> $id group by carID";
$result = mysqli_query($conn,$sql);
$num = mysqli_num_rows($result);
if($num >= 3){ //排除当前投票车辆以后,还发现已经给三辆车投过票了,则说明当前是第4辆车,无法投票。如果不排除那就会和之前比如说昨天投的这辆车数据冲突从而无法投3个车子
echo "<script>alert('每人每天最多只能给三辆车投票');history.back();</script>";
exit;
}
//第3个条件
//两次投票之间要求间隔10s以上。
$sql = "select voteTime from votedetail where userID = " . $_SESSION['loggedUserID'] . " order by id desc limit 0,1";
//得到最新的投票,即可让数据列降序排列然后第一条最大值则为最新的那条数据插入时间,把他作为voteTime
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
//说明此用户曾经投过票
$info = mysqli_fetch_array($result);
if(time() - $info['voteTime'] <= 10){
//说明投票间隔未超过60s,不可以投票
echo "<script>alert('两次投票之间,必须间隔10s ');history.back();</script>";
exit;
}
}
//第4个条件
//IP投票限制。限制一个IP一天只能投15票
$sql = "select 1 from votedetail where from_unixtime(voteTime,'%Y-%m-%d') = CURRENT_DATE() and ip = '".getIp()."'";
//得到一个ip的所有票数
if(mysqli_num_rows($result)>=15){
//说明当前IP地址已经投过15票了
echo "<script>alert('一个IP地址一天之内最多只能投15票。');history.back();</script>";
exit;
}
//确认可以投票
//第1步操作,更新carnum,把票数加一
$sql1 = "update carinfo set carnum = carNum + 1 where id = $id";
//第2步操作,更新votedteail表,更新投票内容
$sql2 = "insert into votedetail (userID, carID, voteTime, ip) VALUES ('".$_SESSION['loggedUserID']."','$id','".time()."','".getIp()."')";
//引入事务机制
mysqli_autocommit($conn,0); //取消上面两个SQL语句自动提交
$result1 = mysqli_query($conn,$sql1);
//echo "1:".mysqli_error($conn);
$result2 = mysqli_query($conn,$sql2);
//echo "2:".mysqli_error($conn);
if($result1 and $result2){
//两个sql操作都为真表示操作成功
mysqli_commit($conn);//提交操作
echo "<script>alert('投票成功');location.href='index.php';</script>";
}
else{
mysqli_rollback($conn);//sql语句操作失败 立即回滚 取消前面的插入数据
echo "<script>alert('投票失败');history.back();</script>";
}
function getIp()
{
if ($_SERVER["HTTP_CLIENT_IP"] && strcasecmp($_SERVER["HTTP_CLIENT_IP"], "unknown")) {
$ip = $_SERVER["HTTP_CLIENT_IP"];
} else {
if ($_SERVER["HTTP_X_FORWARDED_FOR"] && strcasecmp($_SERVER["HTTP_X_FORWARDED_FOR"], "unknown")) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
if ($_SERVER["REMOTE_ADDR"] && strcasecmp($_SERVER["REMOTE_ADDR"], "unknown")) {
$ip = $_SERVER["REMOTE_ADDR"];
} else {
if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'],
"unknown")
) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = "unknown";
}
}
}
}
return ($ip);
}