/api.php
PHP | 76 lines | 74 code | 1 blank | 1 comment | 4 complexity | 2f55703244805d3585cea47d908f230d MD5 | raw file
- <?php
- // 指定允许其他域名访问
- header('Access-Control-Allow-Origin: *');
- header('Access-Control-Allow-Credentials: true');
- include_once("conn.php");
-
- $type=isset($_GET["type"])?$_GET["type"]:null; /*get是获取、update是修改、delete是删除、add是添加*/
- $id=isset($_GET["id"])?$_GET["id"]:null;
- switch ($type){
- case "getProjects":
- getLists($conn,'projects',8,'desc','id,title,thumb,time,type');/*('数据库连接','表名称','每页条数','排序','查询字段')*/
- break;
- case "getProjectInfo":
- getOne($conn,'projects',$id,'*');/*('数据库连接','表名','id','查询字段')*/
- break;
- case "getArticles":
- getLists($conn,'article',8,'desc','id,title,thumb,time,type');
- break;
- case "getarticleInfo":
- getOne($conn,'article',$id,'*');
- break;
- case "insertProjects":
- addOne($conn,"projects");
- break;
- default:
- echo("没有参数");
- }
- function getLists($conn,$table,$size,$sort,$field){
- mysql_query("SET NAMES 'UTF8'",$conn);
- $page =isset($_GET['page'])?$_GET['page']:1; //获取查询页数,如果没有get到page,默认就是第一页!
- if(!preg_match('/^\d+$/',$page) || $page < 1) $page = 1; //如果输入的不是数字 或者小于1 默认第一页
- $table=$table; //获取要查询的数据表
- $pageSize =$size; //每页多少条
- $result_pag_num = mysql_query("SELECT COUNT(*) AS count FROM $table"); //获取数据表中总记录条数
- $row = mysql_fetch_array($result_pag_num);
- $count = $row['count']; //返回记录总条数
- $no_of_paginations = ceil($count / $pageSize); //计算出总页数
- if($page > $no_of_paginations) $page = $no_of_paginations; //如果请求页码大于总页数 默认最后一页
- $start = ($page - 1) * $pageSize; //sql查询起始位置
- $query_pag_data = "SELECT $field from $table order by id $sort LIMIT $start, $pageSize";
- $result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
- $arrList = array(); //初始化列表数组
- $arr=array();
- while($row = mysql_fetch_array($result_pag_data)){
- array_push($arrList,$row); //将每条信息push到列表数组中
- }
- $array = array(
- "count" => $count, //总条数
- "pageSize" => $pageSize, //每页条数
- "pageCount" => $no_of_paginations, //总页数
- "thisPage" => $page,//当前页码
- "list" => $arrList //列表
- );
- echo json_encode ($array);
- }
- function getOne($conn,$table,$id,$field){
- $sql="select $field from $table where id='$id'";
- $info=array();
- mysql_query("set names 'utf8'");
- mysql_query("SET CHARACTER SET UTF8");
- mysql_query("SET CHARACTER_SET_RESULTS=UTF8'");
- $result=@mysql_query($sql) or die();
- while($row=mysql_fetch_array($result)){
- $info=$row;
- }
- echo json_encode($info);
- }
- function addOne($conn,$table){
- $data=$_GET["data"];
- $arr=explode(",",$data);
- foreach($arr as $key=>$value){
- echo $key."=>".$value;
- }
- }
- close();
- ?>