1

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?

4
  • in your for loop for (...) { if($data[$c] == 5) { // insert query} }. Is this what you were looking for? Commented May 11, 2013 at 12:01
  • I think, THINK after reading the question 4-5 times that he wants dynamic fields in his query, not to run the same query multiple times. Commented May 11, 2013 at 12:03
  • Can you explain the part of the "dynamic" columns? How can the same table have different number of columns? Commented May 11, 2013 at 12:03
  • Tanks a lot Tivie. Every table column is fixed but table is dynamic.This script is for dynamic table Commented May 11, 2013 at 13:09

3 Answers 3

2

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 .= ")";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Can you help me to increase my reputation
0

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} ; ";

Comments

0

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, "','") . "')";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.