双倍时间数据入到MySQL中


double time data is getting inserted in mysql

每次我尝试插入数据时,都会在数据库中插入两次或三次,第二次而不是数据,值0入。我也需要使用提交按钮插入数据,但它不起作用。

hello_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');
}

代码中的问题:

  1. 您在数据库中获得空行,因为您没有验证数据,您需要验证是否从帖子中获取。
  2. 您在使用return后回显"嗨,欢迎",由于return,它不能返回用户名。
  3. 始终在函数末尾加载视图文件,而不是在顶部。

您需要验证用户,因为它将插入一行,即使您尚未提交表单也是如此。

将你的 heloo() 替换为:

public function heloo()
{
    // User will be false if there wasn't any post data
    $user=$this->input->post('user');
    if($user !== false) {
        // The form was submitted
        $user = array(
            'user_name'=>$user
        );
        $this->load->model("heloo_model");
        $this->heloo_model->insert_user($user);
        echo "hi, welcome:"."$user";
    } else {
        // The form needs to be shown here
        $this->load->view('heloo_view');
    }
}

此代码最初将显示表单,直到用户提交表单并创建行。