【问题标题】:Can't insert data via rest api无法通过rest api插入数据
【发布时间】:2020-04-15 09:52:50
【问题描述】:

我尝试在 codeigniter 中使用 rest api 来插入数据。

我试试这个

    public function sensor_post(){
    $data = array(
                'sensor_id'   => $this->input->post('sensor_id'),
                'value'       => $this->input->post('value'));

    $insert = $this->db->insert('measurement', $data);

    if ($insert) {
        $this->response($data, 200);
    } else {
        $this->response(array('status' => 'fail', 502));
    }

  }

然后调用 http://localhost/rest_iot/index.php/iot/sensor?sensor_id=1&value=37

我在邮递员中尝试这个,我得到这样的错误。我想我已经填写了值,为什么会发生这种情况?

   <h1>A Database Error Occurred</h1>
    <p>Error Number: 1048</p>
    <p>Column 'sensor_id' cannot be null</p>
    <p>INSERT INTO `measurement` (`sensor_id`, `value`) VALUES (NULL, NULL)</p>
    <p>Filename: C:/xampp/htdocs/rest_iot/system/database/DB_driver.php</p>
    <p>Line Number: 691</p>

【问题讨论】:

    标签: php api codeigniter


    【解决方案1】:

    如果您在 URL 中发送数据,则您是通过 GET 发送数据。但是,您的代码正在尝试接收通过 POST 发送的数据。 我假设在 codeigniter 中您可以简单地编写如下代码以将其作为 GET 接收:

            'sensor_id'   => $this->input->get('sensor_id'),
            'value'       => $this->input->get('value')
    

    【讨论】:

      【解决方案2】:

      您是通过 GET 还是 POST 发送数据?假设 $this-&gt;post('sensor_id') 您正在寻找 POST 但通过 GET sensor_id=1&amp;value=37 发送。

      通过 POST 方法发送数据或...通过 GET 检索

      【讨论】:

        【解决方案3】:

        您的帖子字段中缺少输入。

        public function sensor_post()
            {
                $data = array(
                    'sensor_id'   => $this->input->post('sensor_id'),
                    'value'       => $this->input->post('value')
                );
        
                $insert = $this->db->insert('measurement', $data);
        
                if ($insert) {
                    $this->response($data, 200);
                } else {
                    $this->response(array('status' => 'fail', 502));
                }
            }
        

        这对你有用。

        【讨论】:

        • 你能用这个打印出post value来检查它吗? print_r($this->input->post());退出;
        • 我得到 array(2) { ["sensor_id"]=> NULL ["value"]=> NULL } Array ( ) 并且我已经填写了值
        • 您在发布数据中收到 Null 值意味着它们是 API 方面的一些问题。您没有从 API 方面获得价值。
        猜你喜欢
        • 2012-06-10
        • 1970-01-01
        • 2020-05-17
        • 2011-10-09
        • 2019-03-04
        • 1970-01-01
        • 2020-05-22
        • 2021-03-19
        • 1970-01-01
        相关资源
        最近更新 更多