Reputation: 63
I have an order form. It has 10 textfields for the user to input a quantity. How do you store the inputs to an array and insert to a db field(separated by comas)? Note: It is NOT required to input on all the textfields. For instance, the inputs are 1,2,3,4..it should appear in the db field also 1,2,3,4
examples and descriptions would be great. I'm relatively new to this.
Upvotes: 3
Views: 2990
Reputation: 11859
suppose this is your form: if you are only bothering about order array nothing else like corresponding key.
<form action="submit.php" method="post">
<input type="text" name="order[]" />
<input type="text" name="order[]" />
<input type="text" name="order[]" />
<input type="text" name="order[]" />
<input type="submit" />
</form>
your submit.php:
<?php
$data ="";
foreach($_POST["order"] as $key=>$val){
if(isset($val) && $val !="")
$data.=$val.",";
}
$data=trim($data);
echo $data;// use data
Note: do not use mysql use PDO or mysqli instead. mysql is deprecated.
Upvotes: 0
Reputation: 5625
So, let's say you have a table with four text fields - fieldOne
, fieldTwo
, fieldThree
, fieldFour
.
Your html form
should look like this (i'm skipping irrelevant parts).
<form method="POST">
<textarea name='data[fieldOne]'></textarea>
<textarea name='data[fieldTwo]'></textarea>
<textarea name='data[fieldThree]'></textarea>
<textarea name='data[fieldFour]'></textarea>
</form>
Now, your PHP
code:
$data = $_POST['data']; // PHP converts names like data[fieldOne] into arrays.
foreach ($data as $key => $value) {
$fieldNames[] = "`{$key}`"; //field names for our insert statement - `fieldOne`, `fieldTwo`, etc...
$values[":{$key}"] = strip_tags($value);
}
$stmt = $pdo->prepare("INSERT INTO `tableName` (".implode(', ', $fieldNames).") VALUES (".implode(", ", array_keys($values)).")"; // If you're not using PDO and prepared statements you're doing it wrong, so i absolutely recommend you learning that if you haven't already.
$stmt->execute($values);
That should do the trick.
Notice, using prepared statements frees you from manually escaping your data. However, if you're concerned about XSS
attacks, you still should use strip_tags
of a filter
extension.
Upvotes: 3
Reputation: 6922
HTML
<form action="my_page_that_processes_orders.php" method="post">
<input type="text" name="order[product1]" />
<input type="text" name="order[product2]" />
<input type="text" name="order[product3]" />
<input type="text" name="order[product4]" />
<input type="submit" />
</form>
my_page_that_processes_orders.php
$data = $_POST["order"];// Advisable to perform checks for security reasons (not going to do it)
$aux = '';
foreach($data as $product => $qty) {
// Do whatever you please with the data.
$aux .= "$product $qty,"; // For instance.
}
$string_to_insert = rtrim($aux, ",");
// Insert it in DB or do more processing stuff.
Hope it helps.
Kind regards.
Upvotes: 2