我是这项工作的新手我在视图文件夹中创建了这样的简单表单:
<form action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Book Title</td>
<td><input type="text" name="title" /></td>
</tr>
<tr>
<td>Book Author</td>
<td><input type="text" name="author" /></td>
</tr>
<tr>
<td>Book Image</td>
<td><input type="file" name="image" /></td>
</tr>
<tr>
<td>Book Description</td>
<td><input type="text" name="content" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" /></td>
</tr>
</table>
</form>
&#13;
我在控制器中收到表格数据,如下所示:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('insert/post');
$title = $this->input->post('title');
$author = $this->input->post('author');
$image = $this->input->post('image');
$content = $this->input->post('content');
}
}
&#13;
但如何将这些数据插入到数据库中,可以帮助您使用简单的代码。
答案 0 :(得分:2)
你去吧
应用/控制器/的welcome.php
<?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');
}
}
应用/模型/ Exemple_model.php
<?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();
}
}
答案 1 :(得分:0)
$this->db->query(
'INSERT INTO tbl (a, b, c, d) VALUES (?, ?, ?, ?)',
array($a, $b, $c, $d)
);
或
$this->db->insert('tbl', array($a, $b, $c, $d));
获取最后一个插入ID:
$idOfInsertedData = $this->db->insert_id();