How can I get values from dual inputs

I am making a flashcard program and I want to get value from all inputs named front[] and back[], I know only how to get value from one of them in foreach, how I can get also from back?

foreach($_POST['front'] as $front){
    $mysqli->query("INSERT INTO data (front, back) VALUES('$front', '$back')")
}

Will there be the same number in both arrays, or will the numbers differ?

Also, for efficiency and security, you should use prepared statements.
Prepare your query, with placeholders, just once, outside of the loop.
Then in the loop execute the query, changing the bound parameters in each iteration of the loop.
Never put user input data directly into a query like that, it is prone to SQL injection. Prepared statments will reduce that risk.
Also, when running the same query over and over in a loop with different values, preparing once, then only executing multiple times, with different values, is far more efficient.

2 Likes

I am new at the PHP and yet I don’t know much about security etc., but I will also consider your advices.

This code is used for creating flashcard decks so I have two inputs in a row (front and back of the card) and if I fill them, I can add another two inputs for making a next card, I can even do 100 inputs.

So the number of inputs vary.
But is the the number of front and back inputs always equal?

1 Like

Yes, they are always equal

That makes things simpler:-

// Prepare only once
$stmt = $mysqli->prepare("INSERT INTO data (front, back) VALUES(:front, :back)");

foreach($_POST['front'] as $key => $front){
   $stmt->bindParam(':front', $front);
   $stmt->bindParam(':back', $_POST['back'][$key]);
   $stmt->execute();
}

Forgive my ignorance of mysqli, I don’t use it in preference to PDO, so I don’t really know the syntax, but I think this should work, but it may not.
You may also want to validate the input first.

1 Like

I think that I will cope with it. Thank you for help.

It does assume that both front and back arrays have the same keys, which if you did not specify keys, will be default numbered keys, 0 to however many.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.