4
$rate=[10,20,40,50,70];

How do I insert the value in below query?

$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)
      VALUES('{$rate[0]}','{$rate[1]}', '{$rate[2]}','{$rate[3]}','{$rate[4]}')";

$stmt =connection::$pdo->prepare($sql);
$stmt->execute();

I tried below but it inserts same value in all column for a record and creates new record for each new value:

foreach($rate as $key->$value)
{  
    $sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)
          VALUES('{$value}','{$value}', '{$value}','{$value}','{$value}')";

    $stmt =connection::$pdo->prepare($sql);
    $stmt->execute();

Edited based on answer given

public function rentalRate()
    {

$rate = implode("','",$this->rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
$stmt =connection::$pdo->prepare($sql);
        $stmt->execute();
        unset($rate);
    }
112233
  • 2,406
  • 3
  • 38
  • 88

4 Answers4

5

Simply use implode and that's it

$rate = [10,20,40,50,70];
$rate = implode("','",$rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
echo $sql;
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0

Foreach is not useful in this case, because you want to integrate more than one array element in one query and you do not have a multidimensional array. Just use your first query:

$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('{$rate[0]}','{$rate[1]}', '{$rate[2]}','{$rate[3]}','{$rate[4]}')";

And - if you really want to use foreach:

$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES(";
foreach($rate as $value)
    $sql .= "'$value', ";
$sql = rtrim($sql, ", ") . ")";
Richard
  • 2,840
  • 3
  • 25
  • 37
0

just simple (note implode will only work with integers, without need to quoate)

 $rate=[10,20,40,50,70];
 $r_sql = '';
 foreach($rate as $r) {
     $r_sql.="'$r',";
 }
 $r_sql = trim($r_sql,',');
 $sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES(".$r_sql.")";
donald123
  • 5,638
  • 3
  • 26
  • 23
  • 1
    See the answer of Uchiha, very nice solution for strings (Of course, the array should be walked through before to prevent SQL injections). – Richard Jul 09 '15 at 09:47
0

Normally arrays are inserted into a different table and all tools are geared towards this. It is usually better not to fight the tools or it is likely to run into unforseen problems.

If we add a

table rental_day(id(int), rental_id(int,fk), rate(money))

Then for all the items in the array we just insert the item into one row in rental_day

later when we need the info back we can query for it like

select * from rental_day d inner join rental r on d.rental_id=r.id where r.id=something

and you will get all the info from rental_day and rental in one query.

Esben Skov Pedersen
  • 4,437
  • 2
  • 32
  • 46