0

I am trying to build a sql string which can insert multiple row in one query itself please have a look on the following code .
I have an array called

conversion_rates which is something like this array(1) { [11]=> float(507.6) }

and the code which I am trying to execute is something like this

public function updateExRate(){/*Updates the table in the DB with exchange rates*/

    $sql =  'INSERT INTO conversor '.
           '( Sl_no  , Ex_rate,Idmoneda,Time_update) VALUES'.foreach($this->conversion_rates as $k =>$v){.' ( NULL ,'.$v.
           ','.$k.','.time().');'};

    var_dump($this->conversion_rates);
    echo 'Running... '.$sql.'<br>';
    $this->parent->parent->database->query($sql);  

}

So this is a function to update the db where i am trying to build a sql statement which is inserting multiple row and to inert the values I am using that foreach loop inside the string and that is where I am getting the error

Passerby
  • 9,715
  • 2
  • 33
  • 50
Vikram Anand Bhushan
  • 4,836
  • 15
  • 68
  • 130

2 Answers2

1

You can try this:

$sql = 'INSERT INTO conversor "( Sl_no , Ex_rate,Idmoneda,Time_update) VALUES ';

        foreach($this->conversion_rates as $k =>$v)
        {
            $sql .= '( NULL ,'.$v.','.$k.','.time().');';

        }

        $sql .= '"}';
Vikas Umrao
  • 2,800
  • 1
  • 15
  • 23
  • small mistake in the code :) $sql = '( NULL ,'.$v.','.$k.','.time().');'; it should be $sql .= '( NULL ,'.$v.','.$k.','.time().');'; I mean '.' was missing because of that the string was being overwritten – Vikram Anand Bhushan Feb 27 '14 at 07:14
0

you can use this :

$sql =  'INSERT INTO conversor ( `Sl_no`  , `Ex_rate,Idmoneda`,`Time_update`) VALUES ';

foreach($this->conversion_rates as $k =>$v)$sql.="( NULL ,'$v','$k',".time()."),";

$sql=rtrim($sql, ",").";";
YamaCasis
  • 1
  • 1