Search code examples
phphtmlmysqlserver-side

Link another value to a textarea element when posting to use as an id [PHP]


I have been trying to figure out a way to do this for a couple hours now. So, I am creating a form that generates textarea tags for every 'client' I selected, this part is easy for me. My problem is linking each text area to the clients id I have created for them so when I post the textarea input to my database I can post their id with it as well. Are there any ideas to post a value with each textarea? Any help is greatly appreciated...

MY html code for textarea

<td><?php echo "<textarea name='comments[]' cols='10'> </textarea>"?></td>

I TRY to post the text through a foreach loop, one by one

The variable holding the info I need is wrapped up like this

<?php $clientlevel = $client.":".$i;?>

I then use explode() to parse it


Solution

  • Some pseudo code to show how you might assign the client id to each textarea and then process the POSTed data..

    /* query the db using preferred methods */
    $sql='select * from users where selected=1';
    $res=$db->query($sql);
    
    echo "<form method='post'>";
    $i=0;
    /* loop through recordset to generate textareas with client id assigned to comment */
    while( $rs = $db->fetch($res) ){
        $uid=$rs->userid;
        echo "<td><textarea col=50 rows=3 name='comments[\"{$uid}\"]'>Comments.. $i</textarea></td>";
        $i++;
    }
    echo "<input type='submit'></form>";
    
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        echo '<div>', print_r($_POST,true), '</pre>';
    
    
        /* specifically target and process the comments */
        $comments=!empty( $_POST['comments'] ) ? $_POST['comments'] : false;
        if( $comments ){
            foreach( $comments as $uid => $text ){
                echo 'User: '.$uid.' Comment:'.$text.'<br />';
            }
        }
    }
    
    
    
    Will output something like:
    Array
    (
        [comments] => Array
            (
                ["client_1"] => Comments.. 0
                ["client_2"] => Comments.. 1
                ["client_3"] => Comments.. 2
                ["client_4"] => Comments.. 3
                ["client_5"] => Comments.. 4
                ["client_6"] => Comments.. 5
                ["client_7"] => Comments.. 6
                ["client_8"] => Comments.. 7
                ["client_9"] => Comments.. 8
                ["client_10"] => Comments.. 9
            )
    
    )