Domanda

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));
È stato utile?

Soluzione

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

Altri suggerimenti

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.

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 = ?

This

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

should do it...

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 = ?)', ?, ?, ?)'

     ';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top