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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With