【问题标题】:REST app + codeigniter + databaseREST 应用程序 + codeigniter + 数据库
【发布时间】:2015-08-21 07:45:43
【问题描述】:

我做了一个 REST 应用程序 + codeigniter + 数据库,如下:https://github.com/chriskacerguis/codeigniter-restserver,效果很好,很棒。

现在我的 json 文件正在获取静态数据,我如何从数据库中获取数据?

我写了一个文件,我可以从数据库中获取数据,但是我不知道如何从数据库中获取 json 中的数据,你们能帮帮我吗?谢谢。

该文件返回给我的静态 json,完美运行,我想从数据库中获取数据。

/controllers/hello.php

<?php
include (APPPATH.'/libraries/REST_Controller.php');
class Hello extends REST_Controller {
    function world_get(){
        $data = new stdClass();
        $data->name = 'Mark ';
        $this->response($data, 200);
    }
}

下面的这些文件我可以从数据库中获取数据,但是在 html 中,我如何获取 json 格式的数据?

/controllers/site.php

<?php

Class Site extends CI_Controller {
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function index(){

        $this->load->model('data_model');
        $data['rows'] = $this->data_model->getAll();
        $this->load->view('home', $data);
    }

}

/models/data_model.php

<?php 

class Data_model extends CI_Model {
    function getAll(){
        $q  = $this->db->query("SELECT * from data");
        if($q->num_rows() > 0) {
            foreach ($q->result() as $row) {
                $data [] = $row;
            }
            return $data;
        }
    }
}

views/home.php

<htmL>

    <body>


        <pre>

        <?php foreach ($rows as $r)
        {
            echo '<h1>' . $r->title . '</h1>';
        }
        ?>
    </pre>

        <?php foreach ($rows as $r) : ?>


            <h1> <?php echo $r->author; ?></h1>
            <h1> <?php echo $r->contents; ?></h1>

        <?php endforeach; ?>
    </body>


</htmL>

【问题讨论】:

    标签: php mysql json codeigniter rest


    【解决方案1】:

    你正在做API。返回数据你不需要调用view。你可以这样做

    function index()
    {
        $this->load->model('data_model');
        $data = $this->data_model->getAll();
        $this->response($data, 200);
    }
    

    你的模型函数没问题,但你可以让它变得简单。

    function getAll()
    {
        return $this->db->get('data')->result();    
    }
    

    【讨论】:

      【解决方案2】:

      只需在您的控制器中使用json_encode 并在您的模型文件中进行少量更改

      控制器

      function index(){
           $this->load->model('data_model');
           $result= $this->data_model->getAll();// change this line
           $data['rows']= json_encode($result);// add this line
      
          $this->load->view('home', $data);
      
      }
      

      型号

      <?php 
      
      class Data_model extends CI_Model {
          function getAll(){
              $q  = $this->db->query("SELECT * from data");
              if($q->num_rows() > 0) {
                return $q->result();
              }else{
                return false;
               }
          }
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-05
      • 2013-03-25
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多