DragonSlayer
DragonSlayer

Reputation: 837

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

Upvotes: 0

Views: 7148

Answers (3)

Johan
Johan

Reputation: 76537

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.

Upvotes: 5

Bas Slagter
Bas Slagter

Reputation: 9929

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.

Upvotes: 3

Brent Friar
Brent Friar

Reputation: 10609

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.

Upvotes: -3

Related Questions