Jump to content

[SOLVED] Post Form Content To Array


alconebay

Recommended Posts

How would I process the content of a form so that it will go into an array instead of having to create a variable for each text area?

 

Form Example:

 

<form name="form" method="post" action="process.php">

<textarea name="name1" cols="25" rows="3">Name1</textarea>

<textarea name="name2" cols="25" rows="3">Name2</textarea>

<textarea name="name3" cols="25" rows="3">Name3</textarea>

</form>

 

Process.php:

<?php
$name1=$_POST['name1'];
$name2=$_POST['name2'];
$name3=$_POST['name3'];
$query = "INSERT INTO names (name1, name 2, name3) //....and on it goes...
?>

 

How would I change the process.php so that I would not have to make a variable for each name but instead an array? Once its in an array how would I insert it into the database? Would it be anything like this?:

 

<?php
$query = "INSERT INTO names (name1, name 2, name3) VALUES ('".$name[0]."' , '".$name[1]."', '".$name[2]."')";
?>

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/128600-solved-post-form-content-to-array/
Share on other sites

I would change the names of the textareas to an array, like so:

<form name="form" method="post" action="process.php">
<textarea name="name[1]" cols="25" rows="3">Name1</textarea>
<textarea name="name[2]" cols="25" rows="3">Name2</textarea>
<textarea name="name[3]" cols="25" rows="3">Name3</textarea>
<input name="submit" value="Send Info">
</form>

Then you can process the information like

<?php
if (isset($_POST['submit'])) {
  $tmpq = array();
  foreach ($_POST['name'] as $k => $val) 
       if (strlen(trim(stripslashes($val))) > 0) $tmpq[] = 'name' . $k . " = '" . mysql_real_escape_string(trim(stripslashes($val))) . "'";
  if (!empty($tmpq)) {
      $q = 'insert into names set ' . implode(', ',$tmpq);
      $rs = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
  }
}
?>

 

The above code uses the alternative format of the Insert command that is the same as the Update command.

 

Note: untested, so there may be syntax errors.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.