Search code examples
phpcodeigniterinsert-select

INSERT INTO.....SELECT FROM


i want to put calory as the first value of fruits, i couldn't do it, can anyone help?

   $sql = 'INSERT INTO fruits VALUES('', ?, ?, ?)'
          SELECT calory
          FROM diet
          WHERE fruit = ?
         ';

   $this->db->query($sql, array($a, $b, $c, $d));

Solution

  • The correct syntax is :

    INSERT INTO "table1" ("column1", "column2", ...)
    SELECT "column3", "column4", ...
    FROM "table2"
    

    in your case this should be :

    INSERT INTO fruits (calory)
    SELECT calory
    FROM diet
    WHERE fruit = ?
    

    (if "calory" is the name of the column in the table "fruits")