【问题标题】:Codeigniter doesn't get ID and update database not workCodeigniter 没有获得 ID 并且更新数据库不起作用
【发布时间】:2018-10-25 18:22:36
【问题描述】:

我已经使用 Codeigniter 学习了一个简单的更新脚本,但我遇到了一个问题,数据不会更新,因为它没有获取 id。但是当我尝试在 mysql 中使用 SQL 语法运行查询时,它工作并更新了数据。

这是我的桌子(会员):

id | Name | Job | Age
_____________________
1  |Joe   |None | 30
2  |Mike  |None | 23
3  |Alice |None | 21

这是我通过 id 获取数据的控制器脚本:

public function update_now($id)
  {

    $name = $this->input->post('name');
    $job  = $this->input->post('job');
    $age  = $this->input->post('age');

    $query = $this->m_update->update_data($name, $job, $age);
    if ($query > 0) {
        }
    redirect('data_detail');

这是我的模型脚本:

function update_data($name, $job, $age)
{
  $query=$this->db->query("update member SET name='$name', job='$job', age='$age' where id='$id'");
 } 

当我尝试测试脚本时,更改了where id=1 它可以工作,但是当我更改为$id 时它不起作用,它没有获得数据 ID。我错过了什么吗? 感谢您提供所有解决方案和建议。

【问题讨论】:

标签: database codeigniter


【解决方案1】:

在您的表单中,您需要使用 URL 中的 ID 提交数据,如下所示:

<form method="post" action="<?= base_url("route/$id") ?>">
    ....
</form>

然后您必须使用以下内容将该 id 发送到您的模型中:

$data = array(
    'name' => $this->input->post('name'),
    'job' => $this->input->post('job'),
    'age' => $this->input->post('age')
);

$query = $this->m_update->update_data($id, $data);

if ($query) {
     redirect('data_detail');
}

此时你的模型应该改为:

function update_data($id, $data) {
  return $this->db->where('id', $id)->update("member", $data);
} 

有关更多信息,您应该在此处查看用户指南:

Codeigniter 3 - Updating data using the query builder

【讨论】:

    【解决方案2】:

    您尚未将 $id 传递给模型中的函数 update_data

    修改代码如下:

    控制器

    public function update_now($id)
    {
    $name = $this->input->post('name');
    $job  = $this->input->post('job');
    $age  = $this->input->post('age');
    
    $query = $this->m_update->update_data($name, $job, $age, $id);
    if ($query > 0) {
        }
    redirect('data_detail');
    }
    

    型号

    function update_data($name, $job, $age, $id)
    {
      $query=$this->db->query("update member SET name='$name', job='$job', age='$age' where id='$id'");
    } 
    

    【讨论】:

      【解决方案3】:

      您的表单必须采用以下格式:

      <form method="post" action="<?= base_url("route/$id") ?>">
          ....
      </form>
      

      这样就可以了。

      【讨论】:

      • 这是我的表单格式&lt;form method="post" class="form-horizontal form-label-left" action="&lt;?php echo base_url().'index.php/masterdata/update_now' ?&gt;"&gt;
      • 您传递给 update_now 方法以更新数据的 id 在哪里?
      • 从控制器(编辑功能),首先我从我的视图页面.../edit/1获取ID,然后它根据ID显示数据,然后我在完成编辑后单击提交按钮,它会运行控制器update_now
      • 将从.../edit/1 获取的id 值传递给编辑表单视图,并在表单操作中作为第三个参数回显。因此,您将能够在提交表单时获得该 ID。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 2019-02-16
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      相关资源
      最近更新 更多