php數據介面
統一的數據訪問介面PDO
PDO(PHP Data Objects) 擴展為 PHP 訪問資料庫定義了一個輕量級的、一致性的介面,它提供了一個數據訪問抽象層,這樣,無論使用什麼資料庫,用戶都可以通過統一的函數執行來查詢和獲取數據。注意,你並不能使用 PDO 擴展本身執行任何資料庫操作,必須使用一個 database-specific PDO driver (針對特定資料庫的 PDO 驅動)訪問資料庫伺服器。
⑵ php中怎麼把資料庫連接寫成一個介面
我自己封裝的一個
<?php
class AppConfig{
public static $dbParam = array(
'dbHost' => 'localhost',
'dbUser' => 'root',
'dbPassword' =>'',
'dbName' => '資料庫名',
'dbCharset' => 'utf8',
'dbPort' => 3306,
'dbPrefix' => 'test_',
'dbPconnect' => 0,
'dbDebug' => true,
);
}
class Model {
private $version = ''; //mysql版本
private $config = array(); //資料庫配置數組
private $class; //當前類名
public $tablepre = 'ts_'; //表前綴
public $db = ''; //庫名
public $table = ''; //表名
private static $link; //資料庫鏈接句柄
private $data = array(); //中間數據容器
private $condition = ''; //查詢條件
private $fields = array(); //欄位信息
private $sql = array(); //sql集合,調試用
public $primaryKey = 'id'; //表主鍵
//構造函數初始化
public function __construct($dbParam = array()) {
$this->config = (is_array($dbParam) && !empty($dbParam)) ? $dbParam : AppConfig::$dbParam;
$this->connect();
$this->init();
}
//鏈接資料庫
private function connect() {
if($this->config['dbPconnect']) {
self::$link = @mysql_pconnect($this->config['dbHost'], $this->config['dbUser'], $this->config['dbPassword']);
}else{
self::$link = @mysql_connect($this->config['dbHost'], $this->config['dbUser'], $this->config['dbPassword'], true);
}
mysql_errno(self::$link) != 0 && $this->errdie('Could not connect Mysql: ');
$this->db= !empty($this->db) ? $this->db : $this->config['dbName'];
$serverinfo = $this->version();
if ($serverinfo > '4.1' && $this->config['dbCharset']) {
mysql_query("SET character_set_connection=".$this->config['dbCharset'].",character_set_results=".$this->config['dbCharset'].",character_set_client=binary", self::$link);
}
if ($serverinfo > '5.0') {
mysql_query("SET sql_mode=''", self::$link);
}
@mysql_select_db($this->db, self::$link) or $this->errdie('Cannot use database');
return self::$link;
}
//表基本信息初始化
protected function init() {
$this->class = get_class($this);
$this->table = !empty($this->table) ? $this->table : strtolower($this->class);
$this->table = $this->tablepre . $this->table;
return $this;
}
//設置屬性值
public function __set($name, $value) {
//exit($value);
$this->data['fields'][$name] = $value;
}
//獲取屬性值
public function __get($name) {
if(isset($this->data['fields'][$name])) {
return($this->data['fields'][$name]);
}else {
return NULL;
}
}
//欄位信息處理
private function implodefields($data) {
if (!is_array($data)) {
$data = array();
}
$this->fields = !empty($this->data['fields']) ? array_merge($this->data['fields'], $data) : $data;
foreach($this->fields as $key => $value) {
$fieldsNameValueStr[] = "`$key`='$value'";
$fieldsNameStr[] = "`$key`";
$fieldsValueStr[] = "'$value'";
}
return array($fieldsNameValueStr, $fieldsNameStr, $fieldsValueStr);
}
//條件判斷組裝
private function condition($where = NULL) {
if (is_numeric($where)) {
$where = "WHERE `{$this->primaryKey}`='{$where}' LIMIT 1";
}elseif (is_array($where)){
$where = "WHERE `{$this->primaryKey}` in (".implode(',',$where).")";
}elseif(!empty($this->data['condition'])){
//'預留WHERE', 'order', 'group', 'limit' …………等條件關鍵詞處理介面
$where = $where ? "WHERE {$where}" : "WHERE 1";
isset($this->data['condition']['where']) && $where .= ' AND '.$this->data['condition']['where'];
isset($this->data['condition']['group']) && $where .= ' GROUP BY '.$this->data['condition']['group'];
isset($this->data['condition']['order']) && $where .= ' ORDER BY '.$this->data['condition']['order'];
isset($this->data['condition']['limit']) && $where .= ' LIMIT '.$this->data['condition']['limit'];
}else{
$where = "WHERE {$where}";
}
$this->condition = $where;
return $this;
}
//插入數據
public function insert($data = array(), $replace = false) {
$fields = $this->implodefields($data);
$insert = $replace ? 'REPLACE' : 'INSERT';
$sql = "{$insert} INTO `{$this->db}`.`{$this->table}` (".implode(', ',$fields[1]).") values (".implode(', ',$fields[2]).")";
$this->query($sql);
return $this->getInsertId();
}
//更新數據
public function update($data = array() ,$where = '') {
$numargs = func_num_args();
if ($numargs == 1) {
$where = $data;
$data = array();
}
$fields = $this->implodefields($data);
$this->condition($where);
$sql = "UPDATE `{$this->db}`.`{$this->table}` SET ".implode(', ',$fields[0])." {$this->condition}";
$this->query($sql);
return $this->getAffectedRows();
}
//刪除數據
public function delete($where = NULL) {
if(!is_array($where) && strtolower(substr(trim($where), 0, 6)) == 'delete'){
$sql = $where;
}else{
$this->condition($where);
$sql = "DELETE FROM `{$this->db}`.`{$this->table}` {$this->condition}";
}
$this->query($sql);
return $this->getAffectedRows();
}
//查詢數據
public function select($where = NULL, $fields = '*') {
if(!is_array($where) && strtolower(substr(trim($where), 0, 6)) == 'select'){
$sql = $where;
}else{
$this->condition($where);
$sql = "SELECT {$fields} FROM `{$this->db}`.`{$this->table}` {$this->condition}";
}
return $this->fetch($this->query($sql));
}
//查詢一條數據
public function getOne($where, $fields = '*') {
$data = $this->select($where, $fields = '*');
if($data) {
return $data[0];
}
return array();
}
//查詢多條數據
public function getAll($where, $fields = '*') {
$data = $this->select($where, $fields = '*');
return $data;
}
//結果數量
public function getCount($where = '', $fields = '*') {
$this->condition($where);
$sql = "SELECT count({$fields}) as count FROM `{$this->db}`.`{$this->table}` {$this->condition}";
$data = $this->query($sql);
if($data){
return @mysql_result($data,0);
}
return 0;
}
//執行sql語句(flag為0返回mysql_query查詢後的結果,為1返回lastid,其他返回影響行數,默認為2返回影響行數)
public function query($sql, $flag = '0', $type = '') {
if ($this->config['dbDebug']) {
$startime = $this->microtime_float();
}
//查詢
if ($type == 'UNBUFFERED' && function_exists('mysql_unbuffered_query')) {
$result = @mysql_unbuffered_query($sql, self::$link);
} else {
//exit($sql);
$result = @mysql_query($sql, self::$link);
}
//重試
if (in_array(mysql_errno(self::$link), array(2006,2013)) && empty($result) && $this->config['dbPconnect']==0 && !defined('RETRY')) {
define('RETRY',true); @mysql_close(self::$link); sleep(2);
$this->connect();
$result = $this->query($sql);
}
if ($result === false) {
$this->errdie($sql);
}
if ($this->config['dbDebug']) {
$endtime = $this->microtime_float();
$this->sql[] = array($sql,$endtime-$startime);
}
//清空操作數據
$this->data = array();
return $flag == '0' ? $result : ($flag == '1' ? $this->getInsertId() : $this->getAffectedRows());
}
//返回結果$onlyone為true返回一條否則返回所有,$type有MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH
public function fetch($result, $onlyone = false, $type = MYSQL_ASSOC) {
if($result){
if ($onlyone) {
$row = @mysql_fetch_array($result, $type);
return $row;
}else{
$rowsRs = array();
while($row=@mysql_fetch_array($result, $type)) {
$rowsRs[] = $row;
}
return $rowsRs;
}
}
return array();
}
//可以運行SELECT,SHOW,EXPLAIN 或 DESCRIBE 等返回一個資源標識符的語句得到返回結果數組
public function show($sql, $onlyone = false) {
return $this->fetch($this->query($sql), $onlyone);
}
// 使用call函數處理同類型函數
private function __call($name, $arguments) {
$callArr = array('on', 'where', 'order', 'between', 'group', 'limit');
if (in_array($name, $callArr)) {
$this->data['condition'][$name] = $arguments[0];
}else{
$this->errdie("function error: function {$name} is not in ($this->class) class exist");
}
return $this;
}
//返回最後一次插入ID
public function getInsertId() {
return @mysql_insert_id(self::$link);
}
//返回受影響行數
public function getAffectedRows() {
return @mysql_affected_rows(self::$link);
}
//獲取錯誤信息
private function error() {
return ((self::$link) ? @mysql_error(self::$link) : @mysql_error());
}
//獲取錯誤信息ID
private function errno() {
return ((self::$link) ? @mysql_errno(self::$link) : @mysql_errno());
}
//獲取版本信息
function version() {
if(empty($this->version)) {
$this->version = mysql_get_server_info(self::$link);
}
return $this->version;
}
//列印錯誤信息
private function errdie($sql = '') {
if ($this->config['dbDebug']) {
die('</BR><B>MySQL ERROR</B></BR>
SQL:'.$sql.'</BR>
ERRNO:'.$this->errno().'</BR>
ERROR:'.$this->error().'</BR>');
}
die('DB ERROR!!!');
}
//獲取時間微妙數
private function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
//析構函數
public function __destruct() {
echo '<hr>';
$this->config['dbDebug'] && print_r($this->sql);
//unset($this->result);
//unset($this->condition);
//unset($this->data);
}
}
class user extends Model {
//public $db = 'qsf_mvc';
//public $table = 'user';
public $primaryKey = 'uid';
}
$userObj = new user();
//---------------------------------------插入數據方法一-----------------------------------------
//模擬ActiveRecord模式 插入數據
$userObj->username = 'hoho';
$userObj->passwd = '1478522';
$userObj->email = '[email protected]';
$userObj->sex = 1;
$userObj->desc = '清潔工';
$insetId = $userObj->insert();
if ($insetId > 0) {
echo "插入ID為:{$insetId}<BR>";
}
//---------------------------------------插入數據方法二-----------------------------------------
//直接數組做參數插入數據
$userArr = array(
'username' => 'hoho',
'passwd' => '1478522',
'email' => '[email protected]',
'sex' => '1',
'desc' => '廚師',
);
$insetId = $userObj->insert($userArr);
if ($insetId > 0) {
echo "插入ID為:{$insetId}<BR>";
}
//---------------------------------------更新數據方法一----------------------------------------
$userObj->username = 'h111oho';
$userObj->passwd = '1478511122';
$userObj->email = '[email protected]';
$userObj->sex = 1;
$userObj->desc = '清潔工';
$affectedRows1 = $userObj->update(89);
if ($affectedRows1 > 0) {
echo "影響行數為:{$affectedRows1}<BR>";
}
//---------------------------------------更新數據方法二----------------------------------------
//更新記錄(傳遞參數的方式和insert操作一樣)
$userArr = array(
'username' => 'hohoho',
'passwd' => '1474rr4448522',
'email' => '[email protected]',
'sex' => '0',
'desc' => '廚師qq',
);
$affectedRows = $userObj->update($userArr, $insetId);
if ($affectedRows > 0) {
echo "影響行數為:{$affectedRows}<BR>";
}
//----------------------------------------查詢數據----------------------------------------------
$userRs0 = $userObj->select(8); //單個主鍵值
//print_r($userRs0);
$userRs1 = $userObj->select(array(1,5,8)); //多個主鍵值的數組
//print_r($userRs1);
$userRs2 = $userObj->select('select count(*) as count from user where uid > 20'); //直接完整sql語句
//print_r($userRs2);
$userRs3 = $userObj->select("`uid` > 0"); //where條件
//print_r($userRs3);
$userRs4 = $userObj->getOne("`uid` > 0"); //獲取單條記錄
//print_r($userRs4);
$usersRs5 = $userObj->getAll("`uid` > 0"); ////獲取所有記錄
//print_r($usersRs5);
$usersRs6 = $userObj->limit('0,10')->where('uid > 100')->order('uid DESC')->group('username')->select();
//print_r($usersRs6);
//----------------------------------------刪除數據-----------------------------------------------
//刪除操作傳遞參數的方式和select操作一樣
$userObj->delete(60); //單個主鍵值
$userObj->delete(array(1,5,8)); //多個主鍵值的數組
$userObj->delete('delete from user where uid > 100'); //直接完整sql語句
$userObj->delete("`uid` > 100"); //where條件
$userObj->limit('5')->where('uid > 80')->delete();
//----------------------------------------特殊查詢-----------------------------------------------
$userShowRs = $userObj->show('show create table user', true); //獲取特殊查詢的結果,第二個參數代表返回一條結果還是所有的結果
⑶ php怎麼改變數據介面的真實路徑
<?php
include("connection.php");
$perNumber=10; //每頁顯示的記錄數
$page=$_GET['page']; //獲得當前的頁面值
$count=mysql_query("select count(*) from user"); //獲得記錄總數
$rs=mysql_fetch_array($count);
$totalNumber=$rs[0];
$totalPage=ceil($totalNumber/$perNumber); //計算出總頁數
if (!isset($page)) {
$page=1;
} //如果沒有值,則賦值1
$startCount=($page-1)*$perNumber; //分頁開始,根據此方法計算出開始的記錄
$result=mysql_query("select * from user limit $startCount,$perNumber"); //根據前面的計算出開始的記錄和記錄數
while ($row=mysql_fetch_array($result)) {
echo "user_id:".$row[0]."<br>";
echo "username:".$row[1]."<br>"; //顯示資料庫的內容
}
if ($page != 1) { //頁數不等於1
?>
<a href="fenye.php?page=<?php echo $page - 1;?>">上一頁</a> <!--顯示上一頁-->
<?php
}
for ($i=1;$i<=$totalPage;$i++) { //循環顯示出頁面
?>
<a href="fenye.php?page=<?php echo $i;?>"><?php echo $i ;?></a>
<?php
}
if ($page<$totalPage) { //如果page小於總頁數,顯示下一頁鏈接
?>
⑷ PHP如何寫一個給外人上傳數據的介面
介面的流程.
建立控制器(訪問地址)->審核訪問者身份(token)->驗證提交數據是否符合類型(validate
)->處理接收數據(邏輯流程)->返回結果(json字元串).
其中要注意是否存在跨域,如果跨域要做跨域處理,例如返回jsonp.
⑸ php中的API介面怎麼寫
api介面是具有的特定功能的程序代碼塊,作用是產生或者處理傳輸數據;
其存在的意義在於,不同語言之間的正常交流,包括iOS,java,PHP,C等,但是所有的程序語言都支持Json和Xml數據類型,所以介面產生數據基本都是json或者xml文件。
怎麼寫?
其實就是正常的功能類和方法,調用時產生需求功能對應的數據,僅此而已,在沒有什麼復雜的邏輯。
⑹ php怎麼寫api介面
api和WEB開發一樣,首先是需要一些相關參數,這類參數,會有客戶端傳過來,也許是POST或GET,這需要制定統一規范或者開發團隊約定好。而有了參數後,可根據應用需求,完成其數據處理。數據邏輯處理完後,返回客戶端所需要用到的相關數據,例如:任務狀態、內購結果、玩家信息等等數據怎麼返給客戶端?直接輸出的形式,如:JSON、XML、TEXT 等等。
⑺ PHP 的API介面
使用PHP寫api介面是經常做的,PHP寫好介面後,前台就可以通過鏈接獲取介面提供的數據,而返回的數據一般分為兩種情況,xml和json,在這個過程中,伺服器並不知道,請求的來源是什麼,有可能是別人非法調用我們的介面,獲取數據,因此就要使用安全驗證
原理
從圖中可以看得很清楚,前台想要調用介面,需要使用幾個參數生成簽名。
時間戳:當前時間
隨機數:隨機生成的隨機數
口令:前後台開發時,一個雙方都知道的標識,相當於暗號
演算法規則:商定好的運算規則,上面三個參數可以利用演算法規則生成一個簽名。前台生成一個簽名,當需要訪問介面的時候,把時間戳,隨機數,簽名通過URL傳遞到後台。後台拿到時間戳,隨機數後,通過一樣的演算法規則計算出簽名,然後和傳遞過來的簽名進行對比,一樣的話,返回數據。
演算法規則
在前後台交互中,演算法規則是非常重要的,前後台都要通過演算法規則計算出簽名,至於規則怎麼制定,看你怎麼高興怎麼來。
我這個演算法規則是
時間戳,隨機數,口令按照首字母大小寫順序排序
然後拼接成字元串
進行sha1加密
再進行MD5加密
轉換成大寫。
⑻ php中如何調用介面以及編寫介面代碼詳解
可以用curl獲取借樓的信息。
所謂介面,就是提供一個url,只要你滿足它要求的參數,就能得到你要的數據。比如你拿到一個介面,帶上所需的參數,復制到地址欄同樣能得到。不過最好用程序得到。file_get_contents也可以用,不過有局限性。所以我建議用curl。給你一個函數,挺好用的。
function request($url,$https=true,$method='GET',$data=null){
$ch = curl_init();//初始化,得到資源
curl_setopt($ch, CURLOPT_URL,$url); //請求數據的路徑
curl_setopt($ch, CURLOPT_HEADER,false);//是否輸出頭
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //不直接輸出結果
//curl_setopt ($ch, CURLOPT_SAFE_UPLOAD, 0);//兼容php之後的版本
if($https){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //是否驗證主機
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //是否進行證書驗證
}
if($method=='POST'){
curl_setopt($ch, CURLOPT_POST, true); //POST傳輸
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //傳輸數據
}
$content_json = curl_exec($ch);
if ($content_json === false) {
return "網路請求出錯: " . curl_error($ch);
}
curl_close($ch);
return $content_json;
}
⑼ PHP怎麼做介面
php做簡訊介面其實有2中
一種是直接post數據到對方的api
另外一種是通過soket來進行發送數據包
一般現在都是post形式進行發送數據了
socket的模式很少
⑽ 關於php 調用數據介面 實現網頁邏輯的問題
當然是JSP啦。。。下面給你找了下資料 。 強勢: 1、一處編寫隨處運行。這是一個程序員的夢想,也是從前的程序員的惡夢,為了在不同的平台間運行,使許多程序員一行行的重寫代碼。在這一點上java已經給了我最完美的答案它做的要比php更出色,除了系統之外,你的代碼不用做一點更改的。 2、系統的多台平支持。我已經在差不多所有平台上見到了一致的java servlet/jsp的Web Server/Application Server……系統它可以讓你在任意環境做開發,在任意環境進行系統部署,在任意環境擴展。相比asp/php的局限性是顯面易見的。 3、強大的的可伸縮性。從只有一個小的jar文件就可以運行servlet/jsp到由多台伺服器進行集群和負載均橫,到多台Application進行事務處理、消息處理......一台伺服器到無數以伺服器,Java顯示了一個巨人的生命力。 4、多樣化和功能強大的開發工具支持。這一點與asp很像,java已經有了許多非常優秀的開發工具而且有許多可以免費得到,並且其中的許多已經可以順利的運行於多種平台之下。如果你細心的使用它們會發現比自己第一面看到它們時的功能要強大的多。 弱勢: 1、與ASP一樣,Java的一些優勢正是它致命的問題所在。正是由於為了跨平台的功能,為了極度的伸縮能力,所以極大的增加了產品的復雜性。這么說,它在擴展時需要的分成多少塊,哪么java系統中就有多少種產品。所以你要以看到jre、jdk、jsdk、jswdk……,實際上它們只要有效的搭配在一起,就可以產生強大的效能,密不可分,但是對於一位初學者來說:「有沒有搞錯!難道讓我運行一個jsp就要這么多亂七八糟的東西!」 2、從出現的第一天起就被對手痛罵的:「慢如老牛」。真的,我在第一次運行我的jsp時,我竟然以為我的機器機而將哪個進程給kill了!第一次編繹、運行對於使用者來說真是一場惡夢,在開發時我經常晚上做夢在看WinNT的任務管理器CPU格全綠時等著降下來的樣子和感覺。 3、技巧還是技巧。一個短處就一定要付出代價的。Java的運行速度是用將class常駐內存來完成的,所以它在一些情況下所使用的內存比起用戶數量來說卻實是「最低性能價格比」了。另一方面來說,它還需要硬碟空間來存儲一系列的.java文件和.class文件以及對應的版本文件。 4、缺少系統性的資料。這也許不該說,但是sun在國內做的卻實很差勁,java的資烊在國內極少,到現在我還沒有在書店裡看到一本jsp的書,而對java體系的論述書更是少而又少,與java相關的書(中文版)到現在不過三位數。而再看看之中大量的具然還在講Visual J++或是Java 1.1這樣的陣年舊貨。 總結: 適用人群:具有較強學習能力和耐心的開發人員。投入低但是希望擁有較大的伸縮能力的應用。 適用平台:……(太多而只不再一一列說)適用應用:Internet/Intranet高可靠性應用、Internet/Intranet與Client/Server結合的應用系統 學習方式:Java的Doc文檔和java站點中的一系文檔Internet的源代碼資源(對不起大家,真的不能提出更好的建議了,再有的就是大家的能力和運氣,以及Inetnet上網友的幫助了) 推薦開發工具:JBuilder/Visual Age for java(這個我沒用過,但是有人強力推薦)/Sun Forte for JavaKAWA 推薦開發環境:Windows NT/Windows 2000開發系統JBuilder 3.5(它能成為Web Server,甚至不再需要其它的工具)Tomcat 3.1JDK 1.3(可以不安裝)Access 2000/P II 266/128M RAM/9G HD 推薦應用環境(最少):RedHat Linux 6.2/MySQL 3.22/Apache 1.3.12/Tomcat 3.1/JDK 1.3Beta/PIII 500/512M RAM/9G HD 推薦應用環境(最佳):Solaris 8/Sybase 11/iPlanet Enterprise Web Server 4.1/JDK 1.3Beta/Sun Netra T1/1G RAM/18G HD