dongzenglin8292 2017-04-19 06:14
浏览 494
已采纳

使用postman获取get请求以获取一个对象。 cloud9上的数据库

I am trying to obtain just one object with this get method. The one with ID 27.

This is the get method I"m performing

enter image description here

This is a select from my database.

mysql> select * from researchers;
+------+------+
| id   | name |
+------+------+
|   27 | sam  |
|   17 | sma  |
|   19 | bee  |
|    2 | ggt  |
+------+------+
4 rows in set (0.00 sec)

The output should be [{"id":"27","name":"sam"}]

.

.

. These are all the PHP and html files I'm using in this

index.php

<?php
require_once("db/db.php");
require_once("controllers/researchers_controller.php");
?>

controllers/researchers_controller.php

<!-- source: http://victorroblesweb.es/2013/11/18/tutorial-mvc-en-php-nativo/ -->
<?php

    //Calling the Model
    require_once("models/researchers_model.php");
    require_once("models/researchers.php");
    $per=new researchers_model();


    $method = $_SERVER['REQUEST_METHOD'];

//  echo $method;
    switch ($method) {
        case 'POST':
            $input = json_decode(file_get_contents('php://input'),true);
            $data=$per->post_researchers_pdo($input);
            require_once("views/researchers_view_json.php");
            break;      

        case 'GET':
//              echo $method;
                $data=$per->get_researchers_pdo();
                require_once("views/researchers_view_json.php");
            break;  

        case 'PUT':
//          echo $method;
            $input = json_decode(file_get_contents('php://input'),true);
            echo $input->id . " " . $input->name;
            $data=$per->put_researchers_pdo($input);
            require_once("views/researchers_view_json.php");
            break;      

        case 'DELETE':
            $input = json_decode(file_get_contents('php://input'),true);
            $data=$per->delete_researchers_pdo($input);
            require_once("views/researchers_view_json.php");
            break;  

        default:
            echo 'METHOD IS NOT SUPPORTED';
            break;
        }



//Calling the Model
//require_once("models/researchers_model.php");
//$per=new researchers_model();
//$data=$per->get_researchers();

//Calling the View
//require_once("views/researchers_view_json.php");
// require_once("views/researchers_view.html");
?>

db/db.php

<!-- Source: http://victorroblesweb.es/2013/11/18/tutorial-mvc-en-php-nativo/ -->
<?php
class Connect{
    public static function conexion(){
        $conexion=new mysqli("localhost", "root", "", "mvc");
        $conexion->query("SET NAMES 'utf8'");
        return $conexion;
    }


private static $instance = NULL;
public static function conexion_pdo() {
      if (!isset(self::$instance)) {
        $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        self::$instance = new PDO('mysql:host=localhost;dbname=mvc', 'root', '', $pdo_options);
      }
      return self::$instance;
}
}
?>

models/researchers.php

<?php
    class Researchers {
        public $id;
        public $name;

        public function __construct($par_id,$par_name) {
          $this->id = $par_id;
          $this->name = $par_name;
        }
    }
?>

researchers_model.php

<!-- http://victorroblesweb.es/2013/11/18/tutorial-mvc-en-php-nativo/ -->
<?php
class researchers_model{
    private $var_db;
    private $var_researchers;

    public function __construct(){
        $this->var_db=Connect::conexion();
        $this->var_researchers=array();
    }
    public function get_researchers(){
        $query=$this->var_db->query("select * from researchers;");
        while($rows=$query->fetch_assoc()){
            $this->var_researchers[]=$rows;
        }
        return $this->var_researchers;
    }


public  function get_researchers_pdo() {
      $list = [];
      $db = Connect::conexion_pdo();
      $req = $db->query('SELECT * FROM researchers');

      foreach($req->fetchAll() as $res) {
        $list[]= new Researchers($res['id'], $res['name']);
      }
      return $list;
}


public  function post_researchers_pdo($input) {
        try {
                $db = Connect::conexion_pdo();
                $objResearcher=new Researchers($input["id"], $input["name"]);
//                echo $input["id"] . " " . $input["name"];
                $sql = "INSERT INTO researchers (id, name) VALUES (?,?)";
                $pdo_prepare = $db->prepare($sql);
                $pdo_prepare->execute([$objResearcher->id, $objResearcher->name]);

                $objSuccess->message = $db->lastInsertId();
                $objSuccess->code = "success";
                $objSuccess_JSON = json_encode($objSuccess);
                return $objSuccess_JSON;
            }
            catch( PDOException $Exception ) {
                $objError->message = $Exception->getMessage( );
                $objError->code = (int)$Exception->getCode( );
                $objError_JSON = json_encode($myObj);
                return $objError_JSON;
            }

}
}
?>

views/researchers_views.html

<!-- Source: http://victorroblesweb.es/2013/11/18/tutorial-mvc-en-php-nativo/ -->
<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8" />
        <title>Researchers</title>
    </head>
    <body>
    <h1>Researchers</h1>
        <?php
            foreach ($data as $dato) {
                echo $dato["name"]."<br/>";
            }
        ?>
    </body>
</html>

view/researchers_view_json.php

  • 写回答

1条回答 默认 最新

  • douquejituan938904 2017-04-19 08:43
    关注

    you need to select something from database WHERE some condition ,

    so in your function get_researchers_pdo you will need to modify if to accepts where clauses , However it's better to use some query builder or ORM packages , for now and as I don't know your full program context I will add new method called get_researchers_pdo_where to select from your database where id equals some value, and to keep your queries safe for sql injections attacks I will use prepared statements, for more info you may checkout PDO Prepare documentation

    public  function get_researchers_pdo_where($id = null) {
    
          if ($id === false) {
              return false;
          }
    
          $list = [];
          $db = Connect::conexion_pdo();
          $req = $db->prepare('SELECT * FROM researchers where id=:id');
    
          $req->execute(array(':id' => $id));
    
          foreach($req->fetchAll() as $res) {
            $list[]= new Researchers($res['id'], $res['name']);
          }
          return $list;
    }
    

    then you will need to modify your switch case 'GET' to be as follows :

    case 'GET':
        $id = (isset($_GET['id'] ? $_GET['id'] : null);
        $data=$per->get_researchers_pdo_where($id);
        require_once("views/researchers_view_json.php");
    break;
    

    in this part , I'm checking if there are a value passed to id query string or not

    $id = (isset($_GET['id'] ? $_GET['id'] : null);
    

    check out more info about ternary operators.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?