I have a dynamic form generated by a while loop that looks like this:
<form>
<?php while ($questions = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<textarea name="text"></textarea>
<input type="hidden" name="question_id" value="<?php echo $questions['question_id']; ?>">
<?php } ?>
</form>
I am trying to insert each 'response' and 'question_id' into its own row. I am not sure whether to send the $_POST variables as arrays like text[] or do a foreach loop or both?
Essentially I want to do the following:
foreach($_POST) {
$query = $db->prepare("INSERT INTO responses SET text=:text, question_id=:question_id);
$query->bindValue(':text', $_POST['text'], PDO::PARAM_STR);
$query->bindValue(':question_id', $_POST['question_id'], PDO::PARAM_INT);
$query->execute();
}
I have read it is also inefficient to execute the query multiple times like this.
What is the best approach to this?
Easy, you just need to improve your loop a little bit and you only need one query...
$query = $db->prepare("INSERT INTO responses SET text=:text, question_id=:question_id");
foreach ($_POST as $key => $value) {
if($key == "text") {
$query->bindValue(':text', $value, PDO::PARAM_STR);
} else if($key == "question_id") {
$query->bindValue(':question_id', $value, PDO::PARAM_INT);
}
}
$query->execute();
set the id of the textarea array like this
<form>
<?php while ($questions = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<textarea name="text[<?php echo $questions['question_id']; ?>]"></textarea>
<?php } ?>
</form>
then you can loop over the $_POST['text'] array
foreach($_POST['text'] as $k => $val) {
$query = $db->prepare("INSERT INTO responses SET text=:text, question_id=:question_id);
$query->bindValue(':text', $val, PDO::PARAM_STR);
$query->bindValue(':question_id', $k, PDO::PARAM_INT);
$query->execute();
}
Post values are like:
<textarea name="text"></textarea>
And at the Server side:
$_POST["text"]
If you want to Transfer multidimensional Array throu POST, use this:
<textarea name="text[]"></textarea>
<textarea name="text[]"></textarea>
<textarea name="text[]"></textarea>
And at the Server side:
$_POST["text"][0]; //1
$_POST["text"][1]; //2
$_POST["text"][2]; //3
Sure it works with keys:
<textarea name="text[foo]"></textarea>
<textarea name="text[boo]"></textarea>
<textarea name="text[]"></textarea>
And at the Server side:
$_POST["text"]["foo"]; //1
$_POST["text"]["boo"]; //2
$_POST["text"][0]; //3