开发者

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("inse开发者_StackOverflow中文版rt 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??


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


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;
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜