随机生成防伪码及从数据库导出到excel表格
随机生成防伪码及从数据库导出到excel表格
方法/步骤
一、创建数据库
随便你命名数据库名称,我这里的是key,里面也这样一个表security_code,并且表里面有id,time,pici,skey这几个字段。

二、编写需要的代码,并放在你的web环境下
我这里编写了2个php文件,test.php、excel.php
test.php(是访问页面操作的文件)
<?php
header("Content-Type:text/html; charset=utf-8");
mysql_connect('localhost','root','root');
mysql_select_db('Key');
mysql_query('set names utf8');
function createRandomStr($length){
$str = array_merge(range(0,9),range('a','z'),range('A','Z'));
shuffle($str);
$str = implode('',array_slice($str,0,$length));
return $str;
}
if(isset($_POST['submit'])){
$pici=$_POST['pc'];
$sl=$_POST['sl'];
$sql="select skey from Security_code";
$res=mysql_query($sql);
for($j=0;$j<$sl;$j++){
$str=createRandomStr(18);
for($i=0;$i<$sl;$i++){
$row=mysql_fetch_assoc($res);
$str1=$row['skey'];
if($str1==$str){
break 2;
}else{
$datetime=date('Y-m-d H:i:s');
$sql="insert into Security_code(time,skey,pici) values('$datetime','$str','$pici')";
mysql_query($sql);
ini_set('max_execution_time', '300');
break 1;
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>生成防伪码</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<table style="width:600px;">
<tr>
<th>批次:</th>
<td><input name="pc" type="text"></td>
</tr>
<tr>
<th>数量: </th>
<td><input type="text" name="sl" /></td>
</tr>
<tr>
<th> </th>
<td>
<input value=" 生成防伪码 " name="submit" type="submit" onclick="return confirm('确定要生成防伪码吗?')">
</td>
</tr>
</table>
</form>
<form action="excel.php" method="POST">
要导出的批次:<input type="text" name="pici"/><br/>
<input type="submit" name="submit" value="Submit" onclick="return confirm('确定要导出防伪码吗?')" />
</form>
</body>
</html>
excel.php(是从数据库导入excel文档的文件)
<?php
header("Content-Type:text/html; charset=utf-8");
Header( "Content-type: application/octet-stream ");
Header( "Accept-Ranges: bytes ");
Header( "Content-type:application/vnd.ms-excel ");
Header( "Content-Disposition:attachment;filename=test.xls ");
$con = mysql_connect("localhost","root","root");
mysql_select_db("key");
mysql_query('set names utf8');
if(isset($_POST['submit'])){
$pici=$_POST['pici'];
$sql = "select id,time,pici,skey from security_code where pici=$pici";
}
$result = mysql_query($sql,$con);
echo "id\ttime\tpici\tskey";
while ($rs=mysql_fetch_array($result)){
echo "\n";
echo $rs['id']."\t".$rs['time']."\t".$rs['pici']."\t".$rs['skey'];
}
?>
三、测试
1、首先从你的web服务器上访问test.php文件,然后输入生成防伪码的批次和数量,再点击生成防伪码,如图

2、输入要导出的批次,点击导出,再确定下载,如图

3、打开下载的excel文档,里面的就是按批次随机生成的防伪码。
