-1

So how should I do the code?

Let's say my form is:

<form action="check.php" method="POST">
<textarea name="ans[0]"> </textarea>
<textarea name="ans[1]"> </textarea>
<textarea name="ans[2]"> </textarea>
<textarea name="ans[3]"> </textarea>
<input type="submit" />

The check.php:

<?php
include('mysql.php'); // in this file i get connected to my db
foreach($ans as $index)
{
    //I want to make this to do that: 
    mysql_query("UPDATE mytable SET $ans = '$ans[1]' WHERE user = 'Me'"); // How do I make that to update $ans[0] for first loop scan, than in next loop scan $ans[1] then $ans[2] and so on...
}
?>

And yes, I'm soo begginer in these stuff and have no idea how this code should work. Thanks for answers.

Spoke44
  • 910
  • 8
  • 23
Pie
  • 13
  • 6
  • Use $_POST['ans'] to access your posted variables. But even more important, rewrite your SQL because it uses deprecated mysql_* functions and is open to SQL-Injection. – Xatoo Jan 13 '15 at 16:21

2 Answers2

3

First, you don't have to set an index to your textareas :

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

Avoid mysql_ driver to connect to database. Please use PDO instead.

PHP side

if(isset($_POST['ans']) AND is_array($_POST['ans'])){
    $ans = $_POST['ans'];
    foreach($ans as $content){
        //your query
        $db->query("UPDATE table ......");
    }
}
Spoke44
  • 910
  • 8
  • 23
0

I think that this code could help you.

<form action="check.php" method="POST">
    <textarea name="ans[0]"> </textarea>
    <textarea name="ans[1]"> </textarea>
    <textarea name="ans[2]"> </textarea>
    <textarea name="ans[3]"> </textarea>
    <input type="submit" />
</form>
<?php
    $ans = (array) (isset($_POST['ans']) ? $_POST['ans'] : null);

    foreach($ans as $index=>$value)
    {
        $query = "UPDATE mytable SET `$index` = '$value' WHERE user = 'Me'";
    }

Use PDO instead of mysql php library. => https://stackoverflow.com/a/1402096/1016229

Community
  • 1
  • 1
nicolas_b
  • 169
  • 1
  • 8