daniel.tosaba
daniel.tosaba

Reputation: 2563

php function array argument manipulation

i am making insert function that takes $table argument and $cols(as array)argument. it inserts into given table given values:

$db->query("insert into $table({$cols[0]},{$cols[1]}) values('{$_POST[{$cols[0]}]}','{$_POST[{$cols[1]}]})");

this is all nice except i don't how long array is. how to do this??

Upvotes: 2

Views: 198

Answers (2)

alex
alex

Reputation: 490283

One thing you haven't done is escaped the SQL using the correct escaping mechanism.

$postCols = $_POST['cols']; 

foreach($postCols as &$col) {
    $col = '"' . mysql_real_escape_string($col) . '"';
}

$db->query("insert into $table(" . implode(',', $cols) . ") values(" . implode(',', $postCols . ");

Upvotes: 5

Jess
Jess

Reputation: 8700

I would just use some foreach loops

<?php
  $sql = "INSERT INTO $table (";
  foreach ($cols as $col)
      $sql .= "`$col`,";
  $sql = substr($sql,0,-1);
  $sql .= ") VALUES(";
  foreach ($cols as $col)
      $sql .= "'".$_POST[$col]."',";
  $sql = substr($sql,0,-1);
  $sql .= ");";

  echo $sql;
?>

Upvotes: 2

Related Questions