慕课 php 开发APP接口(四)完结

来源:互联网 发布:神盾网络验证破解 编辑:程序博客网 时间:2024/06/05 19:39

#单例模式连接数据库

#新建 Db.php

<?phpclass Db{    static private $_instance;    static private $_connectSource;    private $_dbConfig = array(        'host'=>'127.0.0.1',        'user'=>'root',        'password'=>'qazxswedcvfrt',        'database'=>'mukeapi',    );    private function __construct(){    }    static public function getInstance(){        if(!(self::$_instance instanceof self)){            self::$_instance = new self();        }        return self::$_instance;    }    public function connect(){        if(!self::$_connectSource){            self::$_connectSource  = mysql_connect($this->_dbConfig['host'],$this->_dbConfig['user'],$this->_dbConfig['password']);            if(!self::$_connectSource){                die('mysql connect error'.mysql_error());            }            mysql_select_db('mukeapi',self::$_connectSource );            mysql_query('set names UTF8',self::$_connectSource);        }        return self::$_connectSource;    }}$connect = Db::getInstance()->connect();$sql = "SELECT * FROM `category`";$result = mysql_query($sql,$connect);var_dump($result);

#创建 list.php 文件

<?phprequire_once('./response.php');require_once('./Db.php');$page = isset($_GET['page'])? $_GET['page']:1;$pageSize = isset($_GET['pagesize'])? $_GET['pagesize']:10;if(!is_numeric($page) || !is_numeric($pageSize)){    return Response::show(401,'bu he fa');}$offset = ($page -1) * $pageSize;$sql = "select * from video where status = 1 order by orderby limit {$offset},{$pageSize}";try{    $connect = Db::getInstance()->connect();}catch (Exception $e){    return Response::show(403,'database connect error');}$result = mysql_query($sql,$connect);$videos = array();while($video = mysql_fetch_assoc($result)){    $videos[] = $video;}if($videos){    return Response::show(200,'success',$videos);}else{    return Response::show(401,'bu he fa');}


在mysqladmin 管理工具中执行 sql 语句开是否正确,修改Db的connect 函数的 die 改成

    throw new Exception('mysql connect error');



待续。。。

0 0
原创粉丝点击