Insert data into codeigniter database

Asked

Viewed 1,201 times

0

Say guys all right, I’m having the following doubt:

I need to view and save data in my database but as I will show below I am using Joins to display, for example the name of an author using his primary key. To display this working, but when I use my method to insert data in the table it returns an error with the foreign key, by what I could understand my code is trying to insert the returned name as if it were the foreign key as this key will not exist it of error, below code and images of what I am doing:

My screen from where the author’s name is displayed: inserir a descrição da imagem aqui

My code used to return the data from the above screen:

function history($ccod) {
$this->db->select('dat, cliente, texto, comcod, cnome, username');
$this->db->where('cliente', $ccod);
$this->db->from('comentarios');
$this->db->join('clientes', 'clientes.ccod = comentarios.cliente');
$this->db->join('users', 'users.id = comentarios.autor');
$query = $this->db->get();
return $query->result();
}

My code to enter the data in the database:

function inserir_coment($data) {
    return $this->db->insert('comentarios', $data, "autor.comentarios = user.id");
    }

Error returned when executing this code:

inserir a descrição da imagem aqui

I believe that arranging the syntax to enter the data my problem is solved, but as I am beginner I could not solve alone, for this application I am using Codeigniter 3.1.3.

  • 1

    What does it mean autor.comentarios = user.id ?

1 answer

3


The error is saying that in the table comentarios the column autor is a foreign key that references the table users. I mean, what did you say.

There needs to be a user with the código fmlima4 as in Insert, or need to pass user code.

The third argument here makes no sense, I’ve never seen three arguments for insert and the third is where.

return $this->db->insert('comentarios', $data, "autor.comentarios = user.id");

I think you wanted to do this

 $data["autor"] = $algumValorDaSessaoPorExemplo;
 return $this->db->insert('comentarios', $data);

You can hit this in your View, for example added a input of the kind hidden to store the author’s code, and in your controller where you mount the array $data assign the value of that hidden for the key autor

  • I managed to do as follows in my view I created the following line: <input type="Hidden" name="author" value="1"/> so it saves the data in the database but by changing the code to <input type="Hidden" name="author" value="<? php $_SESSION['login user']['id']; ? >"/> it does not

Browser other questions tagged

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