Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get inputs from multiple textfields to array and insert to db field

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.

like image 567
kim Avatar asked Apr 05 '26 20:04

kim


1 Answers

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.

like image 111
Eternal1 Avatar answered Apr 08 '26 11:04

Eternal1