在MVC中使用oop php在数据库中插入数据

时间:2013-11-21 07:53:00

标签: php codeigniter

在insert / index.php上     页面上的表格

<form action="insert/run" method="post">
<input type="text" name="data"/>
<input type="submit" value="Submit"/>
</form>

在controller / insert.php上 来自此页面的表单呈现

<?php
class Insert extends Controller 
{
function __construct() {
    parent::__construct();
}
function index() {
    $this->view->render('insert/index');
}
    function run()
    {
            $this->model->run();
    }
}

在model / insert_model.php上 模型如何将数据插入数据库

<?php

class Insert_Model extends Model

{

public function __construct()

{

        parent::__construct();

}
    public function run()
    {

        $sth = $this->db->prepare("INSERT INTO data (data) value ");
    }
}

插入查询的工作原理

3 个答案:

答案 0 :(得分:0)

在您的控制器上

 function run() {
        $data  = array();

        $data['data'] = $_POST['data'];

        $this->model->run($data);
    }

在你的模特上

public function run($data) {

    $sth = $this->db->prepare("INSERT INTO data (data) values :data");

    $sth->bindValue(":data", $data['data']);

    $sth->execute();
}

答案 1 :(得分:0)

<form action="insert/run" method="post">

更改为

<form action="<?=site_url('insert/run');?>" method="post">

型号:

//change this
 public function run()
    {

        $sth = $this->db->prepare("INSERT INTO data (data) value ");
    }

//to this

public function run($data)
    {

       $this->db->insert("tablename",$data);
    }

控制器:

//add this to your controller
function run()
    {
            $data = array('column1' => $this->input->post('data')
                          );
            $this->model->run($data);
    }

答案 2 :(得分:0)

//在模型上

    part of code in model

    function run() {
    $data  = array();

    $data['data'] = $_POST['data'];

    $this->model->run($data);
}

//在控制器上

      part of code in controller

      public function run($data)
       {
          $stam =  $this->db->prepare('INSERT INTO data (`data`) VALUES (:data)');

          $stam->execute(array(
           ':data' => $data['data']
                ));
    }

这将是完美的