3

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));
NestedWeb
  • 1,657
  • 2
  • 15
  • 31

5 Answers5

6

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")

Hugo
  • 141
  • 4
0

You can't mix up INSERT ... SELECT and INSERT ... VALUES in one query. Just select the other values as constants in your SELECT statement and you'll be fine:

INSERT INTO fruits
  SELECT calory, ?, ?, ?
  FROM diet
  WHERE fruit = ?
Sirko
  • 72,589
  • 19
  • 149
  • 183
0

This

INSERT INTO fruits SELECT calory, ?, ?, ? FROM diet WHERE fruit = ?

should do it...

shadyyx
  • 15,825
  • 6
  • 60
  • 95
0

When you use placeholders for values, (in your case the question marks) you need to use ->prepare() and not ->query(). Also your SQL syntax is completely wrong. At a guess I think your query should read something like...

$sql = "INSERT INTO fruits VALUES('', ?, ?, ?) WHERE fruit = ?"; // Create query string.

$sth = $this->db->prepare($sql); // Prepare the query.
$sth->bindValue(1,$a); // Bind question marks to values
$sth->bindValue(2,$b); // (I am assuming that a,b,c,d are in
$sth->bindValue(3,$c); // the correct order...
$sth->bindValue(4,$d);
$sth->execute(); // Execute the query to insert the data.
Lucas
  • 1,476
  • 13
  • 20
-1

You mean you need to put the answer of select query into insert query ,please try this

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

     ';
Sanjay
  • 761
  • 14
  • 25