user6571534 user6571534 - 4 months ago 8
SQL Question

Append an INSERT into SQL by a loop

I want to generate an "insert into" SQL by a loop.

$orderrecord='INSERT into counter SET';

for ($rank=0; $rank<10; $rank++)
{ if (array_search($names[$rank],_$POST['v'])!==FALSE)
{ $orderrecord.=" $names[$rank]=1, "; } ;}


The problem is, there will always be 1 extra comma that render the SQL syntax invalid.
"INSERT into counter SET A=1, B=1, C=1," or "INSERT into counter SET , A=1, B=1, C=1". How to tackle this?

Answer
$orderrecord = 'INSERT into counter SET';

for ($rank=0; $rank<10; $rank++) {
   if (array_search($names[$rank], $POST['v']) !== FALSE) {
      $orderrecord.=" $names[$rank]=1, ";
   }
}

$orderrecord = substr($orderrecord, 0, strlen($orderrecord) - 2);