php處理大量數據,每處理一個數據返回客戶端顯示當前狀態的方法。
類似於dedecms生成靜態頁
想法:
實驗過程:
1.創建數據庫和表
create databases handle; create table user( id int unsigned not null auto_increment primary key, name varchar(8), sex tinyint(1) default '1', score int not null, state tinyint(1) );
2.向表中添加數據(不示例)
3.創建index.html客戶端,a.php服務端1,b.php服務端2
Index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>客戶端</title> </head> <body> <button onclick="send('a.php?state=0')">開始請求</button> <div > <span ></span> </div> <script type="text/javascript" src="./jquery-1.10.2.min.js"></script> <script type="text/javascript"> //創建一個模態框 function display(value){ $('span').html(value); } //ajax function send(dizhi){ $.ajax({ type: "get", url: dizhi, success: function(msg){ var arr=JSON.parse(msg); console.log(arr); //alert(arr.value); var tishi="已經處理 "+arr.now +"個,共"+arr.all+"個"; display(tishi); if(arr.now!=arr.all){ send("a.php?now="+arr.now+"&all="+arr.all); }else{ alert("完成!"); } } }); } </script> </body> </html>
a.php:
<?php require('./dbconfig.php'); $link=mysql_connect(HOST,USER,PASS) or die('數據庫鏈接失敗'); mysql_select_db(DBNAME); /* 查詢數據 $sql="select * from user"; $result=mysql_query($sql); $row=mysql_fetch_assoc($result); var_dump($row); */ /* 循環插入 for($i=3;$i<=100;$i++){ $sql= "insert into user(name,score,state) values('z".$i."',".$i.",1)"; mysql_query($sql); } */ /*查詢需要處理的數據總數*/ //isset($_GET['state'])?$_GET['state']:0; if(isset($_GET['state'])){ $sql="select count(*) from user"; $result=mysql_query($sql); $all=mysql_result($result,0); $now=0; header("Location: b.php?all={$all}&now=0"); }else{ header("Location: b.php?all={$_GET['all']}&now={$_GET['now']}"); } /*返回當前處理的數據*/
b.php:
<?php require('./dbconfig.php'); $link=mysql_connect(HOST,USER,PASS) or die('數據庫鏈接失敗'); mysql_select_db(DBNAME); /*返回當前處理的數據*/ //$id=$_GET['id'];//獲取將要處理的id $now=$_GET['now'];//已經處理的個數 $all=$_GET['all'];//總共要處理的個數 $sql="select score from user limit {$now},1"; $result=mysql_query($sql); $value=mysql_result($result, 0); $now++; $arr=array( 'now'=>$now, 'all'=>$all, 'value'=>$value ); //print_r($arr); echo json_encode($arr);
dbconfig.php:
<?php define('HOST','127.0.0.1'); define('USER', 'root'); define('PASS','root'); define('DBNAME','handle');
以上是全部~