Problems with entering and receiving Mysql values with Codeigniter

Asked

Viewed 19 times

0

I am using the Codeigniter framework, I started my studies a few days ago. I am facing some problems for the creation of a CRUD. Some of them are the connection to the database. I try to insert values in the table, but it won’t, and when I insert them through the terminal and print them in PHP it looks like this:

Foto do erro

model_Conta.php:

class Model_conta extends CI_Model{
        public $id;
        public $nome;
        public $idade;
        public $profissao;

        public function conexao(){
            try{
                $conexao = new PDO("mysql:host=localhost;dbname=ListaContatos;charset=utf8", "joao", "");
                return $conexao;

                }catch(PDOException $erro){
                echo "Conexao falhou: ". $erro->getMessage();
            }
        }

        public function inserir($nome, $idade, $profissao){
            $PDO = Model_conta::conexao();
            $PDO->query("INSERT INTO contatos(nome, idade, profissao) VALUES ($nome, $idade, $profissao);");
        }

        public function retorna(){
            $PDO = Model_conta::conexao();
            $contatos = $PDO->query("select * from contatos");    
            foreach($contatos as $contato){
                print_r('<pre>');
                print_r($contato);
            }
        }
    }

Base.php:

public function cadastrar(){
    $nome = $this->input->post('nome');
    $idade = $this->input->post('idade');
    $profissao = $this->input->post('profissao');
    $this->load->model('Model_conta');
    $this->Model_conta->inserir($nome, $idade, $profissao);

}
public function retorna(){
    $this->load->model('Model_conta');
    $this->Model_conta->retorna();
}

Mistakes:

Return of the table with extra values; You are not entering the values in the bank

1 answer

0


Buddy, you’ve got it all wrong. Not is for you to create a connection PDO within a model!

You have to use the Codeigniter database connection, to see how it configures you can see in this link:

https://codeigniter.com/user_guide/database/configuration.html

For some examples of how to use it, you can use this link:

https://codeigniter.com/user_guide/database/examples.html

All codeigniter database documentation is found at this link:

https://codeigniter.com/user_guide/database/index.html

* You are incorrectly naming the Model, you have to use Nome_model and not Model_nome.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.