首页 > 解决方案 > 无法通过rest api插入数据

问题描述

我尝试在 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>

标签: phpapicodeigniter

解决方案


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

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

推荐阅读