Think PHP第五節課:數據查詢接口的實現

數據查詢接口的實現

1、 這一次課也是進行數據的插入和查詢

為了保存傳感器上傳的數據,我們設計了2張數據表

tom_sensorhistory

tom_sensorinfo

Think PHP第五節課:數據查詢接口的實現

因為上面的教程已經交了如何創建表格,下面是表格的參數

1) 傳感器的信息表

tom_sensorhistory

Think PHP第五節課:數據查詢接口的實現

2) 傳感器的歷史表

tom_sensorinfo

Think PHP第五節課:數據查詢接口的實現

2、 在本地的up上配置一下接口的數據

本地的物理地址:H:\UPUPW_AP7.0\htdocs\iot\Application\Weixin\Conf\config.php

Think PHP第五節課:數據查詢接口的實現

需要和上一節課的config.php區分開來,解釋也就不註釋啦。

代碼如下:

return array(
//'配置項'=>'配置值'
//全局的通用配置
'DB_TYPE'=>'mysql',
'DB_HOST'=>'localhost',
'DB_PORT'=>3306,
'DB_USER'=>'root',
'DB_PWD'=>'root',
'DB_NAME'=>'tomdb',
'DB_PREFIX'=>'tom_'
);

3、 打開路徑H:\UPUPW_AP7.0\htdocs\iot\Application\Weixin\Controller\ IndexController.class.php

實現了數據上傳的接口代碼:

//傳入一個數據
public function SensorDataPost($SensorID=0,$CurrentValue=0)
{
if(IS_POST ) //這裡定義了傳輸的方式,GET是可以進行瀏覽器傳輸
{
//把傳感器的值刷新SensorInfo表裡面的CurrentValue
$Info=M('sensorinfo');
$data2=Array('CurrentValue'=>$CurrentValue,'UpdateTime'=>date('y-m-d h:i:s',time()));
$Info->where(array('SensorID'=>$SensorID)) ->save ($data2); //超級重要,我們只希望更新其中一條記錄
//把傳感器的值新增到SensorHistory
$History=M('sensorhistory');
$data=Array('SensorID'=>$SensorID,'SensorValue'=>$CurrentValue);
$code =$History->Add ($data); //受影響的記錄總數,用於新增數據記錄

if($code>0)
{
echo 'success';
}
else
{
echo 'fail2';
}
}
else
{
echo 'fail';
}
}

打開測試軟件看看:

Think PHP第五節課:數據查詢接口的實現

去數據庫裡面查看結果

Think PHP第五節課:數據查詢接口的實現

4、 數據讀回來又幾個問題需要考慮

1) 數據的時間維度去考慮,最新的,且有限個數(查詢當前)

2) 返回數據的總數,返回最新,返回某個時間段,數量是有限的。(分頁查詢)

5、 實現一個數據查詢接口,可以返回整個表的所有記錄

public function GetSensorData1() 

{
header('content-type:text/json;charset=utf-8');
//打開列表
$history=M('sensorinfo');
//讀取列表
$result= $history->order('SensorID desc')->select();
//返回數據記錄
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}

調用數據接口返回數據

Think PHP第五節課:數據查詢接口的實現

6、 如果只想返回一條記錄,而不是整個表

//返回單個數據 

public function GetSensorData($SensorID=1)
{
//header('content-type:text/json;charset=utf-8');
//打開列表
$History=M('sensorhistory');
//$History=M('sensorinfo');
//讀取列表
//$result= $history->select();
$result=$History->where(array('SensorID'=>$SensorID))->order('id DESC')->limit(1)->select();
//返回數據記錄
echo json_encode($result,JSON_UNESCAPED_UNICODE);
//echo json_encode($result);
}

7、 上面這種"->"叫做連貫操作


分享到:


相關文章: