开发者

How to insert form array values into MySQL?

I'm stuck, I want to insert form data from array fields like below into MySQL:

<input type='text' name='name[]' />` and `<input type='text' name='url[]' />

I 开发者_如何学Pythonknow how to output the data for one field like this example

foreach($_POST['name'] as $name)
{
  echo $name;
}

But in my form I have both <input type='text' name='name[]' /> and <input type='text' name='url[]' /> how can I get this to work correctly?


I would try and avoid querying the DB over and over and just put everything in one big insert statement:

$query = "INSERT INTO table1 (name, url) VALUES ";
foreach($_POST['name'] as $i => $name) 
{ 
  // Get values from post.
  $name = mysql_real_escape_string($name);
  $url = mysql_real_escape_string($_POST['url'][$i]);

  // Add to database
  $query = $query." ('$name','$url') ,";
}
$query = substr($query,0,-1); //remove last char
$result = mysql_query($query);

That way you only have to hit the database once, making the insert much faster.
An other benefit is that if the engine supports transactions (InnoDB et al) all inserts happen in a single transaction.


You can use the indexer of your loop like so:

foreach($_POST['name'] as $i => $name) 
{ 
  // Get values from post.
  $name = mysql_real_escape_string($name);
  $url = mysql_real_escape_string($_POST['url'][$i]);

  // Add to database
  $sql = "INSERT INTO `table` (`name`, `url`) VALUES ('".$name."', '".$url."')";
  $result = mysql_query($sql);
} 

Of course, it's a good practice to use mysql_real_escape_string on the values before adding them in your query.


You need to implode your arrays if you want to store all of the values in a single DB field.

$all_names= implode(",", $name[]);

This will put all of your array values in to a single variable, comma separated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜