分类:
2008-03-15 09:56:56
今天修正了一个数据插入Bug并给页面添加了PHP动态分页。
当我们向数据库插入数据时如果不先进行数据校验就会带来一个“由恶意刷新或者错误操作的非正常数据写入”。如果只是手动刷新插入页,造成的危害是有限的,因为我相信没人能坐在那里用自己稚嫩的小爪子玩命的点击10的N次方“刷新”从而给我的数据库带来灾难。但只要稍微有些脚本编辑常识的人都会通过一种简便的方法来用计算机进行自动刷新,那样可就不好玩了。所以我们要建立一种机制来预防这类事情发生。方法有很多种,有基于HTTP的,也有直接操作数据库的。这次我用的是直接对数据库进行预处理,方法很简单:
$sql="insert into matt(first_name, last_name, department, classification, employee_type, date)
values('$first_name','$last_name','$department','$classification','$employee_type',now())";
$sql_check="select count(*) as count_result from matt where first_name like '%".$first_name."%' and last_name like '%".$last_name."%'";
/* 检查输入框是否为空*/
switch($first_name)
{
case is_null($first_name):
echo "Please leave you first_name";
break;
case !is_null($first_name):
switch($last_name)
{
case is_null($last_name):
echo "Please leave your last name!";
break;
case !is_null($last_name):
/* 确定数据库内无重复记录 */
$check=mysql_query($sql_check);
$row=mysql_fetch_array($check);
$count_result=$row['count_result'];
if($count_result==0)
{
$result=mysql_query($sql);
if($result)
{echo "Your information have been submit.
This page will be back to homepage in 2 seconds!";?>
else
{echo "sorry, error!";}
}
else
{echo "Someone has the same first/last name with you.
This page will be back to homepage in 2 seconds!";?>
break;
}
break;
还是来看看动态分页吧。代码写的很清晰,我就不做细讲了:
//预定义变量page
if(isset($_GET['page']))
{ $page=intval($_GET['page']);}
else
{ $page=1;}
/*页数集算法*/
$sql="select count(*) as count from matt";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$count=$row['count'];
if($count)
{
switch($count)
{
case $count<$page_size:
$page_count=1;
break;
case $count%$page_size!=0:
$page_count=(int)($count/$page_size)+1;
break;
case $count%$page_size=0:
$page_count=$count/$page_size;
break;
}
}
/*分页算法*/
switch($page)
{
case $page==1:
$page_string='Next Page | End Page';
break;
case $page<=$page_count&&$page>1:
$page_string='First Page | Previous Page | Next Page | End Page';
break;
case $page=$page_count:
$page_string='First Page|Previous Page|';
break;
}
$start=($page-1)*$page_size;
$sql_result="select * from matt limit $start, $page_size";
/*生成结果集*/
$result=mysql_query($sql_result);
while($row=mysql_fetch_array($result))
{
$id=$row['id'];
$first_name=$row['first_name'];
$last_name=$row['last_name'];
$department=$row['department'];
$classification=$row['classification'];
$employee_type=$row['employee_type'];
$date=$row['date'];
?>
/*实现分页*/
"."Toltal Pages: ".$page_count."
"."Each page will show:".$page_size." items"; ?>
效果图: