2

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

2 Answers 2

5

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

4 Comments

Haha, I've been using C# to much. Completely forgot about the implode function. Your code is a lot cleaner.
looks great, just remember to escape the values and wrap them in quotes. $escAndQuote = function($x) {return "'" . mysql_real_escape($x) . "'";}; $colVals = array_map($escAndQuote, $_POST['cols']);
what does $_POST['cols'] represent?
@Daniel It looks like you get the POST variables directly, in which case you could change the loop to suit.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.