Php 如何在codeigniter中将数据插入数据库?
我是这项工作的新手,我在视图文件夹中创建了如下简单表单:Php 如何在codeigniter中将数据插入数据库?,php,codeigniter,model-view-controller,Php,Codeigniter,Model View Controller,我是这项工作的新手,我在视图文件夹中创建了如下简单表单: 书名 图书作者 图书形象 书名 或 获取最后一个插入ID: $idOfInsertedData = $this->db->insert_id(); 给你 application/controllers/Welcome.php 但如何将这些表单值发送到模型?我将在何处运行此插入查询。@ZubairAli只是将此代码放入您的模型中。我这样做了,但数据仍然没有插入到数据库中,嗯,您一定是做错了什么,当您的sql查询出错时,C
书名
图书作者
图书形象
书名
或
获取最后一个插入ID:
$idOfInsertedData = $this->db->insert_id();
给你
application/controllers/Welcome.php
但如何将这些表单值发送到模型?我将在何处运行此插入查询。@ZubairAli只是将此代码放入您的模型中。我这样做了,但数据仍然没有插入到数据库中,嗯,您一定是做错了什么,当您的sql查询出错时,CodeIgniter会显示一个错误。你的完整代码是什么?你从来没有在代码段中调用过模型,我尝试过的和你定义的一样:你在使用我给你的东西吗?如果是这样,请确保每个变量都在控制器中填充了一个值,如果需要,请将它们转储是的,我正在使用您提供给我的值,并且每个变量都在控制器中填充了一个从表单中获取的值。请不要问问题,只要求有人为您编码。谷歌上有很多教程可以让你编写简单的代码。然后,如果你写的代码不起作用,过来寻求帮助。
$this->db->insert('tbl', array($a, $b, $c, $d));
$idOfInsertedData = $this->db->insert_id();
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
// If you have post data...
if (!empty($_POST)) {
$title = $this->input->post('title');
$author = $this->input->post('author');
$image = $this->input->post('image');
$content = $this->input->post('content');
// Checking if everything is there
if ($title && $author && $image && $content) {
// Loading model
$this->load->model('exemple_model');
$data = array(
'title' => $title,
'author' => $author,
'image' => $image,
'content' => $content
);
// Calling model
$id = $this->exemple_model->insert($data);
// You can do something else here
}
}
// Loading view
$this->load->view('insert/post');
}
}
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Exemple_model extends CI_Model {
public function insert($data) {
// Inserting into your table
$this->db->insert('MyTable', $data);
// Return the id of inserted row
return $idOfInsertedData = $this->db->insert_id();
}
}