Kyle Dunne Kyle Dunne - 6 months ago 8
MySQL Question

Post looped data, then save with PDO

I have

textarea
that are generated based on how many times they're in the table for a certain ID. So some people will have no
textarea
, others will have one, others with two, etc... How can I update the tabled based on these using my example if possible.

Main Page

<?php
$q = $_GET["q"];
$list = $db->prepare("SELECT * FROM Table WHERE ID = ?");
$list->execute(array($q));
$data = $list->fetchAll();
foreach ($data as $row) :?>

<textarea id="TableID<?=$row["TableID"]?>"></textarea>

<?endforeach?>

<div class="button">Save</div>

<script type="text/javascript">
$( '.button' ).click(function() {
var TableID = $("#TableID").attr('id');
var Comment = $("#TableID").val();

$.ajax({
method: "POST",
url: "save.php",
data : {
TableID : TableID,
Comment : Comment
}
});
});
</script>


Save Page

<?php
$Comment = $_POST["Comment"];
$TableID = $_POST["TableID"];

$save = $db->prepare('UPDATE Table
SET Comment = ?
WHERE TableID = ?');
$save->execute(array($Comment,$TableID));
?>

Answer

Rather than generating your textarea elements with different numbered names, which would be very cumbersome to process on the back end:

<textarea name="TableID1"></textarea>
<textarea name="TableID2"></textarea>
<textarea name="TableID3"></textarea>

You can name them so they get placed into a single $_POST variable. To do this, just name them with brackets at the end of the name like this:

<textarea name="TableID[]"></textarea>
<textarea name="TableID[]"></textarea>
<textarea name="TableID[]"></textarea>

On the PHP side, the values for all 3 of the above text areas would be placed into an array with the values at indexes 0, 1, & 2.

In your case, since you want each textarea to be associated with a specific TableID, use an array within an array using TableID as the first key which would look like this:

<textarea name="TableID[12][]"></textarea>
<textarea name="TableID[54][]"></textarea>
<textarea name="TableID[163][]"></textarea>
<textarea name="TableID[180][]"></textarea>

In doing this, you'd be passing the TableID as part of the element name, so you don't need to POST 2 different variables, Comment & TableID, you really just need to POST the Comment (textarea value).

So the code in your foreach loop generating the page would look like:

<textarea id="Comment[<?=$row["TableID"]?>][]"></textarea>

AND your submit code (assuming you wrap your <textarea> elements in a <form>):

$(function () {
    $('form').submit(function () {
        $.post('save.php', $('form').serialize(), function () {
            // do something here if you want
        });
        return false;
    });
});

Once you have your data being neatly posted in a single array, just prepare the statement as you are doing already, then wrap the execute in a loop that iterates through each TableID:

foreach($Comment as $TableID => $CommentText){
    $save->execute(array($CommentText,$TableID));
}