每次我尝试在数据库中插入两到三次数据时,值0将被插入,而不是数据。
我也需要使用submit按钮插入数据,但它不起作用。
你好,con.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Hello_con extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        //$this->load->view('heloo_view');
    }

    public function heloo()
    {

        $this->load->view('heloo_view');
        $user=$this->input->post('user');

        $user = array(
                'user_name'=>$user
                );

         $this->load->model("heloo_model");
         $this->heloo_model->insert_user($user);
         return $user;
         echo "hi, welcome:"."$user";
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

heloo_model.php
<?php
class Heloo_model extends CI_Model {


    public function insert_user($user)
    {
        $this->load->database();
        $this->db->insert("userdetail",$user);

    }

}
?>

heloo_view.php
<html>
<head>
<title>heloo world</title>
</head>
<body>
<p>welcome to heloo world</p>

<form method="post">
Enter your name:
<input type="text" name="user" placeholder="enter your name">
<input type="submit" name="submit" value="sub">
</form>
</body>
</html>

最佳答案

您可以将其用作:

public function heloo()
{
    if(isset($this->input->post('user'))){
        $user = $this->input->post('user');

        $insert = array(
            'user_name'=>$user
        );

        $this->load->model("heloo_model");
        $this->heloo_model->insert_user($insert);
        echo "hi, welcome:".$user;
    }

    $this->load->view('heloo_view');
}

代码中的问题:
您在数据库中获得空行是因为您没有验证数据,您需要验证是否从post获取。
使用return后,您正在回呼“嗨,欢迎”,因为return而无法返回用户名。
始终在函数末尾加载视图文件而不是在顶部。

10-07 16:08
查看更多