Save visitors email (Newsletter) with codeigniter

1

Good morning, I'm a beginner in PHP and codeigniter. I need a light, until I found what I need but not in codeigniter (because my site is in mvc).

This was found and worked on my localhost link , but I have no way to use it after all it does not have Model and Controllers, and I can not understand the Model in codeigniter very well yet.

Does anyone have an understanding of the subject and can you help me?

My intention is to receive the E-mail and Name of the person through a modal in bootstrap and save in my database for future sending of emails to them.

    
asked by anonymous 27.06.2016 / 15:01

1 answer

2

Try the following:

VIEW

<form method="POST" action="http://www.seusite.com.br/usuario/newsletter">
    <label for="nome">Nome</label>
    <input type="text" id="nome" name="nome" required />
    <label for="email">E-mail</label>
    <input type="email" id="email" name="email" required />

    <input type="submit" value="Enviar" />
</form>

CONTROLLER

<?php
class Usuario extends CI_Controller {

    public function __construct() {
        parent::__construct;

        /* Preferencialmente carregue esses helpers e libraries no arquivo 
           application/config/autoload.php
        */
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    }

    public function newsletter() {
        $this->form_validation->set_rules('nome', 'Nome do usuário', 'required');
        $this->form_validation->set_rules('email', 'E-mail do usuário', 'required');

        if ($this->form_validation->run()) { // Se os dados foram recebidos com sucesso
            $nome = $this->input->post('nome');
            $email = $this->input->post('email');

            /* Carrega a classe que trata da tabela do usuário no banco. 
               Este método pega como referência a pasta application/models.
               Se a classe a ser carregada estiver em algum subdoínio, este deve ser informado também. pe.: $this->load->model('dao/UsuarioDAO');
            */
            $this->load->model('UsuarioDAO');
            $this->UsuarioDAO->cadastrarDadosUsuario($nome, $email);

            // Busque inserir códigos de tratamentos de erros caso o banco gere algum erro.

        } else {
            // código de tratamento de erro...
        }
    }
}

MODEL

<?php
class UsuarioDAO extends CI_Model {

    public function __construct() {
        parent::__construct;

        /* Preferencialmente carregue no arquivo application/config/autoload.php 
           A conexão deve estar configurada no arquivo application/config/database.php
        */
        $this->load->database();
    }

    public function cadastrarDadosUsuario($nome, $email) {
        $this->db->query("INSERT INTO usuario (nome, email) VALUES (?, ?)", array($nome, $email));

        // Inserir código de tratamento de erros...
    }
}
    
28.06.2016 / 17:22