无法在PHP API中检索数据

时间:2016-08-28 01:10:24

标签: php rest pdo

我正在构建一个简单的CRUD应用程序,作为Angularjs和PHP的学习练习。我有一个shell页面,mysql后端,一个处理SQL请求的PHP API,我正在使用Angularjs来处理shell页面和API之间的数据流。我正在使用这里建模的API:

http://angularcode.com/demo-of-a-simple-crud-restful-php-service-used-with-angularjs-and-mysql/

到目前为止,我已经测试了这个应用程序的每个组件,除了API之外,一切都运行得很干净。我所做的一切都是修改原始文件,将语法改为PDO,我调整了响应函数,因为现有的函数不起作用。

抽象类:

<?php
class REST {

    public $_allow = array();
    public $_content_type = "application/json";
    public $_request = array();

    private $_method = "";      
    private $_code = 200;

    public function __construct(){
        $this->inputs();
    }

    public function get_referer(){
        return $_SERVER['HTTP_REFERER'];
    }

    /*public function response($data,$status){
        $this->_code = ($status)?$status:200;
        $this->set_headers();
        echo $data;
        exit;
    }*/
    public function response($status, $status_message, $data){
    header("HTTP/1.1 $status $status_message");
    $response['status'] = $status;
    $response['status_message'] = $status_message;
    $response['data'] = $data;

    $json_response = json_encode($response);

}
    private function get_status_message(){
        $status = array(
                    200 => 'OK',
                    201 => 'Created',  
                    204 => 'No Content',  
                    404 => 'Not Found',  
                    406 => 'Not Acceptable');
        return ($status[$this->_code])?$status[$this->_code]:$status[500];
    }

    public function get_request_method(){
        return $_SERVER['REQUEST_METHOD'];
    }

    private function inputs(){
        switch($this->get_request_method()){
            case "POST":
                $this->_request = $this->cleanInputs($_POST);
                break;
            case "GET":
            case "DELETE":
                $this->_request = $this->cleanInputs($_GET);
                break;
            case "PUT":
                parse_str(file_get_contents("php://input"),$this->_request);
                $this->_request = $this->cleanInputs($this->_request);
                break;
            default:
                $this->response('',406);
                break;
        }
    }       

    private function cleanInputs($data){
        $clean_input = array();
        if(is_array($data)){
            foreach($data as $k => $v){
                $clean_input[$k] = $this->cleanInputs($v);
            }
        }else{
            if(get_magic_quotes_gpc()){
                $data = trim(stripslashes($data));
            }
            $data = strip_tags($data);
            $clean_input = trim($data);
        }
        return $clean_input;
    }       

    private function set_headers(){
        header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
        header("Content-Type:".$this->_content_type);
    }
}   
?>

API本身:

<?php
require_once("Rest.inc.php");

class API extends REST {

    public $data = "";


    private $db = NULL;
    private $conn = NULL;
    public function __construct(){
        parent::__construct();              
        $this->dbConnect();             
    }

    /*
     *  Connect to Database
    */
    private function dbConnect(){
        $this->conn = null;

        $servername="myServer";
        $dbname="mySQL";
        $username="myUN";
        $password="myPW";

        try{
            $this->conn = new PDO("mysql:host=$servername;Database=$dbname",$username, $password);
        }catch(PDOException $e){
            echo "Failed:" . $e->getMessage();
        }
        return $this->conn;
    }
    /*
     * Dynmically call the method based on the query string
     */
    public function processApi(){
        //$func = strtolower(trim(str_replace("/","",$_REQUEST['x']))); //<<--NEED TO FIX THIS.  x determines which function to call
        $func = 'quote';
        if((int)method_exists($this,$func) > 0){
            $this->$func();
        }else{
            $this->response(404,'',''); 
        }
    }

    private function quote(){   
        if($this->get_request_method() != "GET"){
            $this->response(406, '', '');
        }
        $id = (int)$this->_request['id'];
        if($id > 0){
            try{
                $sql = "SELECT * FROM mysql.Quotes WHERE ID =:ID";
                $query = $this->conn->prepare($sql);
                $query->bindParam(":ID", $id);
                $query->execute();
                $result = $query->fetchAll(PDO::FETCH_ASSOC);
            }catch(PDOException $e){
                echo "Failed:" . $e->getMessage();
            }

            echo $this->response(200,"Success",$result);    
        }
    }   

// Initiate Library

$api = new API;
$api->processApi();
?>

我知道的一个问题是processAPI()中的注释部分不起作用。它应该抓取URL的初始部分并根据它确定运行哪个函数,但我的服务器不断抛出错误。我暂时的解决方法是硬编码$ func ='quote';

更重要的是,API会在运行时返回一个空对象。它连接到数据库并执行而没有错误,它确实返回了一个设计对象 - 它里面没有任何东西。如果我提取核心组件 - 数据库连接,SQL请求和响应函数 - 并自行运行它们,它们会正确地提取数据并将其传递给shell。因此,REST类或API中的某些内容必须将其搞砸,但我在PHP中还没有足够的方法来找出它出错的地方。我很感激任何反馈。

0 个答案:

没有答案