MD. ABDUL Halim
MD. ABDUL Halim

Reputation: 722

How to use loop in insert's values in php

I would like to use a loop in insert's Values.

For example

$num = count($data);

for ($c=0; $c < $num; $c++) {
    echo $data[$c] . "<br />\n";

}
 $sql = "INSERT INTO $tbl_name VALUES (    '$data[$c]'   )";

If num is 5 then , then column will be created 5. which will be inserted 1 row with 5 columns.

or If num is 8 then , then column will be created 8. which will be inserted 1 row with 8 columns.

In VALUES, How can i use loop or

Since column number is not fixed. so How to insert column data dynamically which row will be created one(1).

Please any suggestion?

Upvotes: 1

Views: 1379

Answers (3)

DevZer0
DevZer0

Reputation: 13535

first of all you need to define 2 array of fields list for the two queries

$col5 = array('field1', 'field2', 'field3', 'field4', 'field5');
$col8 = array('field1', 'field2', 'field3', 'field4', 'field5', 'field6', 'field7', 'field8');

then

$num = count($data);

for ($c=0; $c < $num; $c++) {
    echo $data[$c] . "<br />\n";

}

if ($num == 5) {
    $fields = explode($col5, ",");
} else { //assume its 8 if not 5
    $fields = explode($col8, ",");
}

$sql = "INSERT INTO $tbl_name (" . $fields . ") VALUES ('" . explode($data, "','") . "')";

Upvotes: 0

sybear
sybear

Reputation: 7784

You want this:

foreach ($data as &$piece){
  $piece = "('{$piece}')" ; //Or you can specify anything else
}

$values = implode(", ", $data) ;

$sql = "INSERT INTO $tbl_name VALUES {$values} ; ";

Upvotes: 0

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

Try this

$sql = "INSERT INTO $tbl_name VALUES ( ";
for ($c=0; $c < $num; $c++) {
    $sql .= "'" . $data[$c] . "',";

}
$sql = substr($sql,0,-1); // removes last comma
$sql .= ")";

Upvotes: 2

Related Questions