iOS与php+mysql的数据交换(2)

原文地址:http://www.dotblogs.com.tw/yang5664/archive/2012/03/14/70741.aspx


概念圖
2012 03 15 14 38 36
iOS App與後端資料結合(查詢、新增)
2012 03 15 09 56 39
wsCatalog.php

<?php

abstract class BaseClassWithDB

{

protected $dbLink;

public function __construct()

{

$this->dbLink = mysql_connect('localhost''root''UrPassword')or die('fail to connect DB');

mysql_query("SET NAMES 'utf8'");

mysql_select_db('wsLookingFun',$this->dbLink)or die('fail to select DB');

}

public function __destruct()

{

mysql_close($this->dbLink);

}

protected function toJson($key$code)

{

$code = json_encode(array($key=>$this->urlencodeAry($code)));

//$code = json_encode($this->urlencodeAry($code));

return urldecode($code);

}

 

protected function urlencodeAry($data)

{

if(is_array($data))

{

foreach($data as $key=>$val)

{

$data[$key] = $this->urlencodeAry($val);

}

return $data;

}

else

{

return urlencode($data);

}

}

}

//catalog 資料表

class Catalog extends BaseClassWithDB

{

static private $instance = NULL;

public function __construct()

{

parent::__construct();

}

//singlton

static public function getInstance()

{

if(self::$instance == NULL)

{

self::$instance = new Catalog();

}

return self::$instance;

}

function __get($property)

{

echo "get property values";

}

function __set($property$value)

{

echo "set property values ";

}

//query data 查詢

function getCatalog($timestamp_$format_='json')

{

$query = "select * from catalogs";

$catalogs = array();

$result = mysql_query($query,$this->dbLink)or die('fail to query data!');

if(mysql_num_rows($result))

{

while($catalog = mysql_fetch_assoc($result))

{

$catalogs[] = array('catalog'=>$catalog);

}

}

//output

//json

if($format_=='json')

{

header('Content-type: application/json');

echo $this->toJson('catalogs',$catalogs);

}

}

//insert data 新增

function setCatalog()

{

$catalog__ = file_get_contents('php://input');

$obj = json_decode($catalog__);

$id = $obj->{'id'};

$desc = $obj->{'description'};

 

$insert = "insert into catalogs(id,description)values('$id','$desc')";

if(!mysql_query($insert,$this->dbLink))

echo 'insert fail';

else echo 'insert success';

}

}

 

$timestamp = $_GET['timestamp'];

$format = isset($_GET['format'])?strtolower($_GET['format']):'json';

$action = isset($_GET['action'])?($_GET['action']):NULL;

$catalog_ = Catalog::getInstance();

 

if(!($action=='insert'))

$catalogs = $catalog_->getCatalog($timestamp$format);

else

$catalogs = $catalog_->setCatalog();

 

?>

結果
2012 03 15 11 58 54



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值