phpcodeignitersql-insert

Executing INSERT SQL with CodeIgniter's query() then passing the boolean result to another query() call results in MySQL error


I have a problem with CodeIgniter and Mysql. I am getting an error with a very simple query:

$o = "INSERT INTO usuarios (user, password) VALUES ('deesggsd', 'dsggd')";
$query = $this->db->query($o);
$this->db->query($query);

produces:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1

1

Filename: C:\wamp\www\newWeb\system\database\DB_driver.php

Line Number: 330

But the query is actually executed; the row appears on the database. What i'm doind wrong?

If I execute the same query on phpmyadmin, all is ok.


Solution

  • What you are doing with $query = $this->db->query($o); is executing the query and storing the result to the $query variable. So you've already run the INSERT once which is why it stores properly to the database.

    Now when you try to run $this->db->query($query); you're basically trying to run a mysql procedure using the result (TRUE) as your query string. This is where it throws the error. Make sense?

    Try doing this instead:

    $this->db->insert('usuarios', array(
        'user'     => 'deesggsd',
        'password' => 'dsggd'
    );
    

    I suggest looking into Active Record and how interaction between PHP & mysql work in general. No offense but this is a beginner level mistake.